第一种 使用ExecutorService.isTerminated();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
cachedThreadPool .submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
System.out.println("方法一执行了");
return "方法一返回值";
}
});
cachedThreadPool .submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
System.out.println("方法二执行了");
return "方法二返回值";
}
});
cachedThreadPool.shutdown();
while (true){
if(cachedThreadPool.isTerminated()){
break;
}
Thread.sleep(100);
}
System.out.println("完成");
输出顺序
方法二执行了
方法一执行了
完成
第二种,利用Future.get()方法;
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
//CompletionService<String> completionService=new ExecutorCompletionService(cachedThreadPool);
List<Future<String>> futures=new ArrayList<>();
Future<String> future = cachedThreadPool .submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(5000);
System.out.println("方法一执行了");
return "方法一返回值";
}
});
Future<String> future2 = cachedThreadPool .submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(2000);
System.out.println("方法二执行了");
return "方法二返回值";
}
});
futures.add(future);
futures.add(future2);
for (Future fut : futures) {
String str = fut.get().toString();
System.out.println(str);
}
cachedThreadPool.shutdown();
System.out.println("完成");
输出循序一定是
方法二执行了
方法一执行了
方法一返回值
方法二返回值
完成
如果是ThreadPoolTaskExecutor
@Autowired
ThreadPoolTaskExecutor threadPoolTaskExecutor;
//判断线程是否全部执行结束
while (threadPoolTaskExecutor.getActiveCount() > 0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}