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());
}
})
即使我已经指定ThreadPool
的类型参数为Queue
,Runnable
如何处理这个?
这项任务将如何排队?
这是因为它在排队或执行之前将你的Callable
任务包装为RunnableFuture
。
这个RunnableFuture
实现了Runnable
接口(除了Future
)。
所以所有的callables都可以排队并执行,没有任何问题。
有关更多信息,请查看AbstractExecutorService
来源。