首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否存在使用当前线程的ExecutorService?

是否存在使用当前线程的ExecutorService?
EN

Stack Overflow用户
提问于 2011-07-05 18:25:45
回答 6查看 43K关注 0票数 106

我所追求的是一种兼容的方式来配置线程池的使用。理想情况下,代码的其余部分应该完全不受影响。我可以使用一个只有一个线程的线程池,但这并不是我想要的。有什么想法吗?

代码语言:javascript
复制
ExecutorService es = threads == 0 ? new CurrentThreadExecutor() : Executors.newThreadPoolExecutor(threads);

// es.execute / es.submit / new ExecutorCompletionService(es) etc
EN

回答 6

Stack Overflow用户

回答已采纳

发布于 2011-07-05 21:59:14

这里有一个非常简单的Executor实现(注意,不是ExecutorService ),它只使用当前线程。从"Java并发实践“(必读)中窃取这篇文章。

代码语言:javascript
复制
public class CurrentThreadExecutor implements Executor {
    public void execute(Runnable r) {
        r.run();
    }
}

ExecutorService是一个更复杂的接口,但也可以用同样的方法来处理。

票数 73
EN

Stack Overflow用户

发布于 2013-02-01 12:24:08

你可以使用芭乐的MoreExecutors.newDirectExecutorService(),或者MoreExecutors.directExecutor(),如果你不需要ExecutorService的话。

如果包含Guava太重了,你可以实现一些几乎一样好的东西:

代码语言:javascript
复制
public final class SameThreadExecutorService extends ThreadPoolExecutor {
  private final CountDownLatch signal = new CountDownLatch(1);

  private SameThreadExecutorService() {
    super(1, 1, 0, TimeUnit.DAYS, new SynchronousQueue<Runnable>(),
        new ThreadPoolExecutor.CallerRunsPolicy());
  }

  @Override public void shutdown() {
    super.shutdown();
    signal.countDown();
  }

  public static ExecutorService getInstance() {
    return SingletonHolder.instance;
  }

  private static class SingletonHolder {
    static ExecutorService instance = createInstance();    
  }

  private static ExecutorService createInstance() {
    final SameThreadExecutorService instance
        = new SameThreadExecutorService();

    // The executor has one worker thread. Give it a Runnable that waits
    // until the executor service is shut down.
    // All other submitted tasks will use the RejectedExecutionHandler
    // which runs tasks using the  caller's thread.
    instance.submit(new Runnable() {
        @Override public void run() {
          boolean interrupted = false;
          try {
            while (true) {
              try {
                instance.signal.await();
                break;
              } catch (InterruptedException e) {
                interrupted = true;
              }
            }
          } finally {
            if (interrupted) {
              Thread.currentThread().interrupt();
            }
          }
        }});
    return Executors.unconfigurableScheduledExecutorService(instance);
  }
}
票数 89
EN

Stack Overflow用户

发布于 2015-01-19 16:00:08

Java 8风格:

Executor e = Runnable::run;

票数 74
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6581188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档