java - 如何配置 ExecutorService newFixedThreadPool() 行为?

标签 java executorservice

Oracle定义newFixedThreadPool(1)方法如下,

Creates a thread pool that reuses a fixed number of threads operating off a shared unbounded queue

我可以设置固定的队列大小,例如1,这样我就可以阻止正在处理的新任务,直到当前任务执行完成,甚至使用堆栈而不是队列,当及时工作时,第一个任务可能会在一段时间后无效,因此可能需要固定大小的堆栈。

最佳答案

你不能。 Executors提供了一些常用的静态工厂方法,例如

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

但如果这不是您所需要的,请创建您自己的ThreadPoolExecutor。例如

public static ExecutorService newFixedThreadPoolWithBoundQueue(
        int nThreads,
        int capacity) {

    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>(capacity));
}

or even use stack instead of queue

我不会尝试这样做。

关于java - 如何配置 ExecutorService newFixedThreadPool() 行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36082946/

相关文章:

java - ScheduledExecutorService 可抛出丢失

Java 执行器 : how can I stop submitted tasks?

java - 如何确保生成的id在数据库中不存在

java - ArrayList<String> 类型的完整名称

java - 使用阻塞方法为多个客户端提供服务时的线程池

java - 如何使用 ExecutorService 等待所有线程完成?

java - 将 .html 请求从 Apache 服务器重定向到 Tomcat 服务器

java - 如何访问H2数据库的*.mv.db文件?

java - JSON 解析为 Java - Android 应用程序

java - 将 ExecutorService 与要执行的任务树一起使用