【发布时间】:2018-12-06 00:18:52
【问题描述】:
我有以下代码:
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
10, // corePoolSize
10, // maximumPoolSize
10, // keepAliveTime
TimeUnit.SECONDS,
new LinkedBlockingQueue<>()
);
final List<Callable<MyResponse>> tasks = new ArrayList<>();
final CountDownLatch latch = new CountDownLatch(concurrency);
for (int i = 0; i < 50; i++) {
tasks.add(() -> {
latch.countDown();
latch.await();
return getResponse(); // Returns a MyResponse object.
});
}
final List<Future<ThrottleResponse>> futures = threadPoolExecutor.invokeAll(tasks);
有 50 个任务,但只有 10 个线程可用。根据我的测试结果,代码需要永远运行,我不明白。
invokeAll 方法会发生什么?这段代码中是否有死锁,为什么?我认为threadPoolExecutor 会将挂起的任务放在LinkedBlockingQueue 中并从队列中轮询以执行任务,所以应该没有死锁吧?
【问题讨论】:
-
我想你已经回答了你自己的问题。
-
@shmosel 但我不明白为什么在这种情况下会出现死锁......
-
因为线程数不够...
-
@shmosel 我认为threadPoolExecutor会将挂起的任务放入LinkedBlockingQueue并从队列中轮询执行任务,所以应该没有死锁吧?
-
它会在完成之前的任务后轮询队列,但闩锁不会让它们完成,直到它们都开始。
标签: java concurrency java.util.concurrent