给出以下使用多线程的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
但应用程序永远不会终止。
我是不是该把线接起来?
3条答案
按热度按时间amrnrhlw1#
您需要在程序即将结束时关闭executor框架,并等待它正常终止。。
uwopmtnx2#
应该在评论,但没有足够的声誉。
你应该给执行官打电话。您可以从以下链接获得更多详细信息:对executorservice调用shutdown()的原因
1aaf6o9v3#
我打赌你想添加这样的内容: