我正在尝试编写一个程序,将工作分配给几个 java 工作线程。问题是当我从命令行运行它时它永远不会返回。我没有得到我的提示,最终必须 ctrl-c 关闭程序。
我已将其简化为以下简单的案例
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");
}
}
这个程序的输出是
djc@djc-linux:/local/mnt/workspace/TestExeServ/bin$ java TestExeServ
Start
my message was Hello!
Task is done, it returned 1
done
就是这样。它挂在那里。没有提示。如果我删除 ExecutorService.submit 行,我会得到
djc@djc-linux:/local/mnt/workspace/TestExeServ/bin$ java TestExeServ
Start
done
djc@djc-linux:/local/mnt/workspace/TestExeServ/bin$
程序自然关闭。
我需要在 ExecutorService 上执行一些我没有正确执行的清理任务吗?我假设 .get() 调用加入了线程。不是这样吗?