【问题标题】:How does a ThreadPoolExecutor that is created using the constructor with BlockingQueue<Runnable> as an argument, enqueue Callables?使用 BlockingQueue<Runnable> 作为参数的构造函数创建的 ThreadPoolExecutor 如何将 Callables 排入队列?
【发布时间】:2019-03-09 23:48:06
【问题描述】:

ThreadPoolExecutor 的构造函数将BlockingQueue 的类型参数设为Runnable
假设我有一个像这样声明的ThreadPoolExecutor

ThreadPoolExecutor customThreadPool = new ThreadPoolExecutor(numberOfAvailableProcessors,
                                numberOfAvailableProcessors, 2L,
                                TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<>(),
                                Executors.defaultThreadFactory(),
                                new RejectedExecutionHandler() {
                                    @Override
                                    public void rejectedExecution(Runnable r, ThreadPoolExecutor threadPoolExecutor) {
                                        // Do something here to handle it
                                    }
                                });  

我的问题是什么时候做类似的事情:

customThreadPool.submit(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    return Math.toIntExact(Thread.currentThread().getId());
                }
            })  

即使我已将Queue 的类型参数指定为RunnableThreadPool 如何处理此问题?
此任务将如何排队?

【问题讨论】:

    标签: java threadpoolexecutor callable blockingqueue


    【解决方案1】:

    这是因为它在排队或执行之前将您的Callable 任务包装为RunnableFuture

    这个RunnableFuture 实现了Runnable 接口(除了Future)。

    因此,所有可调用对象都可以毫无问题地排队和执行。

    查看AbstractExecutorService 来源了解更多信息。

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 1970-01-01
      • 2010-12-29
      • 2021-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 2019-06-25
      相关资源
      最近更新 更多