我犯了以下错误:
Executors.newFixedThreadThreadPool
制作游泳池Callable
个对象的列表,以便call
方法依次尝试在相同的线程池上启动任务 invokeAll
结果是执行程序服务队列的死锁。
我读过的Javadoc似乎并没有禁止这套活动。我错过了什么?有没有办法自定义队列或服务,以便这可以工作?
答案 0 :(得分:3)
我对您的问题的理解类似于以下测试用例,其工作原理(如您所说)并且我很乐意在生产中使用。你的例子与此有何不同?
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Scratch {
public static void main(String[] args) throws InterruptedException {
final ExecutorService pool = Executors.newFixedThreadPool(1);
pool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
pool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
System.out.println(new Date() + ": Second callable being run.");
pool.shutdown();
return null;
}
});
System.out.println(new Date() + ": First callable going to sleep...");
Thread.sleep(2000);
System.out.println(new Date() + ": First callable finished!");
return null;
}
});
pool.awaitTermination(2, TimeUnit.MINUTES);
}
}
打印类似:
Mon Feb 20 01:18:00 GMT 2012: First callable going to sleep...
Mon Feb 20 01:18:02 GMT 2012: First callable finished!
Mon Feb 20 01:18:02 GMT 2012: Second callable being run.