我正在尝试编写一个程序,它将在多个Java工作线程中划分工作。问题是,当我从命令行运行它时,它永远不会返回。我没有得到我的提示,最终必须按ctrl-c关闭程序。使用ExecutorService的Java应用程序永远不会关闭
我它简化为以下琐碎的情况下
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestExeServ {
private class ExpensiveTask implements Callable<Integer>{
private final String msg;
public ExpensiveTask(String str){
this.msg = str;
}
@Override
public Integer call() {
System.out.println("My message was " + msg);
return 1;
}
}
private void run()
{
final ExecutorService exeServ = Executors.newFixedThreadPool(2);
Future<Integer> result = exeServ.submit(new ExpensiveTask("Hello!"));
try {
System.out.println(" Task is done, it returned " + result.get());
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[])
{
System.out.println("Start");
TestExeServ tes = new TestExeServ();
tes.run();
System.out.println("Done");
}
}
这个程序的输出是
[email protected]:/local/mnt/workspace/TestExeServ/bin$ java TestExeServ
Start
my message was Hello!
Task is done, it returned 1
done
就是这样。它挂在那里。没有提示。如果我删除ExecutorService.submit行,我得到
[email protected]:/local/mnt/workspace/TestExeServ/bin$ java TestExeServ
Start
done
[email protected]:/local/mnt/workspace/TestExeServ/bin$
程序自然关闭。
是否有一些清理任务需要在ExecutorService上执行,我做得不好?我假设.get()调用加入了线程。情况并非如此吗?
您需要关闭执行程序 –
或者使用生成守护程序线程的线程工厂。 – assylias
或设置标志allowCoreThreadTimeout [ThreadPoolExecutor应用程序没有完成](http://stackoverflow.com/q/30633698/217324) –