使用以 BlockingQueue<Runnable> 作为参数的构造函数创建的 ThreadPoolExecutor 如何使 Callable 入队?
How does a ThreadPoolExecutor that is created using the constructor with BlockingQueue<Runnable> as an argument, enqueue Callables?
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
的类型参数指定为 Runnable
,ThreadPool
如何处理此问题?
这个任务将如何排队?
那是因为它在排队或执行之前将您的 Callable
任务包装为 RunnableFuture
。
此 RunnableFuture
实现了 Runnable
接口(除了 Future
)。
因此所有可调用项都可以毫无问题地排队和执行。
查看 AbstractExecutorService
来源以获取更多信息。
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
的类型参数指定为 Runnable
,ThreadPool
如何处理此问题?
这个任务将如何排队?
那是因为它在排队或执行之前将您的 Callable
任务包装为 RunnableFuture
。
此 RunnableFuture
实现了 Runnable
接口(除了 Future
)。
因此所有可调用项都可以毫无问题地排队和执行。
查看 AbstractExecutorService
来源以获取更多信息。