public class Main {
private static int count = 0;
public static void main(String[] args){
List<Future> resultList = new LinkedList<>();
/**
* Executors.newCachedThreadPool() 创建一个线程缓存池,若60s中线程没有被使用,则会停止线程并从缓存池中移除
* Executors.newScheduledThreadPool() 创建一个固定容量的线程池,里边的线程按照设定的调度时间执行
* Executors.newFixedThreadPool() 拥有固定容量的线程缓存池
* Executors.newSingleThreadExecutor() 容量为一的线程缓存池,只会有一个线程
*/
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=0; i<10; i++){
Future future = executorService.submit(new Callable<String>() {
@Override
public String call() {
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int count = Main.count;
System.out.println(Thread.currentThread().getName() + "..start Main count:..." + count);
Main.count = ++count;
System.out.println(Thread.currentThread().getName() + "..end Main count:..." + Main.count);
return Thread.currentThread().getName();
}
});
resultList.add(future);
}
executorService.shutdown();
for(Future future: resultList){
try {
System.out.println(future.get() + "..is over...");
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
System.out.println("main thread end...");
}
}
pool-1-thread-1 pool-1-thread-2 pool-1-thread-3 pool-1-thread-4 pool-1-thread-5 pool-1-thread-6 pool-1-thread-7 pool-1-thread-8 pool-1-thread-9 pool-1-thread-10 pool-1-thread-1..start Main count:...0 pool-1-thread-2..start Main count:...0 pool-1-thread-3..start Main count:...1 pool-1-thread-2..end Main count:...1 pool-1-thread-1..end Main count:...1 pool-1-thread-3..end Main count:...2 pool-1-thread-1..is over... pool-1-thread-2..is over... pool-1-thread-4..start Main count:...2 pool-1-thread-3..is over... pool-1-thread-4..end Main count:...3 pool-1-thread-4..is over... pool-1-thread-5..start Main count:...3 pool-1-thread-5..end Main count:...4 pool-1-thread-5..is over... pool-1-thread-6..start Main count:...4 pool-1-thread-6..end Main count:...5 pool-1-thread-6..is over... pool-1-thread-7..start Main count:...5 pool-1-thread-7..end Main count:...6 pool-1-thread-7..is over... pool-1-thread-8..start Main count:...6 pool-1-thread-8..end Main count:...7 pool-1-thread-8..is over... pool-1-thread-9..start Main count:...7 pool-1-thread-9..end Main count:...8 pool-1-thread-9..is over... pool-1-thread-10..start Main count:...8 pool-1-thread-10..end Main count:...9 pool-1-thread-10..is over... main thread end... //主线程在所有线程执行完成后结束
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有