给出以下使用多线程的Java示例:
import java.util.concurrent.*;
public class SquareCalculator {
private ExecutorService executor = Executors.newSingleThreadExecutor();
public Future<Integer> calculate(Integer input) {
return executor.submit( () -> {
Thread.sleep(1000);
return input * input;
});
}
public static void main(String[] args) {
try {
Future<Integer> future = new SquareCalculator().calculate(10);
while (!future.isDone()){
System.out.println("Calculating...");
Thread.sleep(300);
}
Integer result = future.get();
System.out.println("we got: " + result);
} catch(InterruptedException | ExecutionException e) {
System.out.println("had exception");
}
}
}
它产生:
java SquareCalculator
Calculating...
Calculating...
Calculating...
Calculating...
we got: 100
但是应用程序永远不会终止。
我想加入线程吗?
答案 0 :(得分:3)
应该置评,但信誉不足。
您应该在执行程序上调用shutdown。您可以从以下链接获取更多详细信息: Reason for calling shutdown() on ExecutorService
答案 1 :(得分:3)
我敢打赌,您想添加以下内容:
finally {
if (executor != null) {
executor.shutdown();
}
}
答案 2 :(得分:2)
您需要在程序结束时关闭执行程序框架,然后等待它正常终止。
executor.shutdown();
try {
executor.awaitTermination(4 * 3600, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}