需要创建ExecutorService的对象

时间:2013-03-18 07:56:39

标签: java multithreading java-ee synchronization

我想在不使用

的情况下创建ExecutorService的对象

newSingleThreadExecutor(),

Executors.newFixedThreadPool()

和,

Executors.newScheduledThreadPool()

怎么做?这是我第一次使用ExecutorService,搜索了很多东西,找出它是如何实例化的,没有定义任何“线程数”但是失败了。

2 个答案:

答案 0 :(得分:3)

java.util.concurrent.Executors内的大多数工厂方法会返回ThreadPoolExecutor的实例或其子ScheduledThreadPoolExecutor。如果你检查ExecutorService的javadoc,那么你会发现这些都是众所周知的实现。

如果您查看java.util.concurrent.Executors的来源代码,可以避免拨打Executors.newCachedThreadPool()来电话:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                              60L, TimeUnit.SECONDS,
                              new SynchronousQueue<Runnable>());
}

答案 1 :(得分:0)

为什么你不想使用工厂方法?

如果您创建一个Executor对象,您可以轻松地创建对象,就像这个工厂方法已经(已经)做了:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
相关问题