@Test
public void testFixedThreadPool() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
final int index = i;
fixedThreadPool.execute(() -> {
try {
log.info("newFixedThreadPool,index:{}", index);
} catch (Exception e) {
log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
}
});
}
fixedThreadPool.shutdown();
while(true){
if(fixedThreadPool.isTerminated()){
log.info("endd");
break;
}
}
log.info("end");
}
@Test
public void testCallable() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
List<Future<String>> resultList = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
final int index = i;
Future<String> future = fixedThreadPool.submit(() -> {
try {
Thread.sleep(2000);
log.info("newFixedThreadPool,index:{}", index);
} catch (Exception e) {
log.info("newFixedThreadPool,index:{},ErrorMsg:{}", index, e.getMessage());
}
return "success";
});
resultList.add(future);
}
resultList.forEach(x -> {
try {
log.info("result:{}", x.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
fixedThreadPool.shutdownNow();
e.printStackTrace();
return;
}
});
log.info("end");
}
https://blog.csdn.net/qq_31441667/article/details/78830395
https://blog.csdn.net/lisheng19870305/article/details/44747741
https://mp.weixin.qq.com/s/GvJvDtMYERHSTVWQaY9BEg
原文:https://www.cnblogs.com/hongdada/p/9662868.html