Java线程完成后悬挂在完成后()
我有简单的测试代码:
public static void main(String[] args) {
CompletionService<Integer> cs = new ExecutorCompletionService<>(Executors.newCachedThreadPool());
cs.submit(new Callable<Integer>() {
public Integer call(){
try{
Thread.sleep(3000); // Just sleep and print
System.out.println("Sleeping thread: " + Thread.currentThread().getId());
}catch(InterruptedException e){
e.printStackTrace();
}
return 10;
}
});
try{
Future<Integer> fi = cs.take();
System.out.println(fi.get());
}catch(Exception e){
e.printStackTrace();
}
}
我运行它,睡3秒钟,然后打印,
Sleeping thread: 14
10
但随后挂在那里,程序没有结束。
发生了什么,如何完成?
I've got simple test code:
public static void main(String[] args) {
CompletionService<Integer> cs = new ExecutorCompletionService<>(Executors.newCachedThreadPool());
cs.submit(new Callable<Integer>() {
public Integer call(){
try{
Thread.sleep(3000); // Just sleep and print
System.out.println("Sleeping thread: " + Thread.currentThread().getId());
}catch(InterruptedException e){
e.printStackTrace();
}
return 10;
}
});
try{
Future<Integer> fi = cs.take();
System.out.println(fi.get());
}catch(Exception e){
e.printStackTrace();
}
}
I run it, sleep 3 seconds, and prints
Sleeping thread: 14
10
But then it hangs there, the program doesn't end.
What's happening, how to make it finish?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如评论中提到的, tgdavies ,您的程序将在+/- 60秒后退出,因为那是默认超时的超时时间
executorService
在opecutors.newcachedthreadpool()
。如果您不想等60秒,则在提交任务后应关闭执行人服务。
例如:
或者,使用自定义
threadfactory
来配置执行器服务以创建守护程序线程。只有在没有正常(非daemon)线程的情况下,执行实际工作的执行人服务不是一个问题,才能做到这一点。As mentioned in the comments by tgdavies, your program will exit after +/- 60 seconds, because that is the default timeout for a thread without tasks in an
ExecutorService
created byExecutors.newCachedThreadPool()
.If you don't want to wait for 60 seconds, you should shutdown the executor service after you're done submitting tasks.
For example:
Alternatively, configure the executor service to create daemon threads using a custom
ThreadFactory
. Only do this if it is not a problem that an executor service that is doing actual work gets "killed" when there are no more normal (non-daemon) threads.