packagecom.yanshu;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;/***@author:yangyuanyuan
* @description:TODO
* @date :2021/1/22 14:38*/
public classThreadPool {public static voidmain(String[] args) {/**FixThreadPool(int n); 固定大小的线程池
* 使用于为了满足资源管理需求而需要限制当前线程数量的场合。使用于负载比较重的服务器。
* pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-2 0
pool-1-thread-2 1
pool-1-thread-3 0
pool-1-thread-3 1
pool-1-thread-4 0
pool-1-thread-4 1
pool-1-thread-5 0
pool-1-thread-5 1
*
**/
//ExecutorService ex=Executors.newFixedThreadPool(5);//for(int i=0;i<5;i++) {//ex.submit(new Runnable() {//
//@Override//public void run() {//for(int j=0;j<2;j++) {//System.out.println(Thread.currentThread().getName()+"\t"+j);//}//
//}//});//}//ex.shutdown();
/*SingleThreadPoolExecutor :单线程池
需要保证顺序执行各个任务的场景
*
* pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-1 0
pool-1-thread-1 1
* /
ExecutorService ex=Executors.newSingleThreadExecutor();
for(int i=0;i<5;i++) {
ex.submit(new Runnable() {
@Override
public void run() {
for(int j=0;j<2;j++) {
System.out.println(Thread.currentThread().getName()+"\t"+j);
}
}
});
}
ex.shutdown();
/*
* CashedThreadPool(); 缓存线程池
当提交任务速度高于线程池中任务处理速度时,缓存线程池会不断的创建线程
适用于提交短期的异步小程序,以及负载较轻的服务器
*
* pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-2 0
pool-1-thread-2 1
pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-1 0
pool-1-thread-1 1
pool-1-thread-3 0
pool-1-thread-3 1
**/ExecutorService ex=Executors.newCachedThreadPool();for(int i=0;i<5;i++) {
ex.submit(newRunnable() {
@Overridepublic voidrun() {for(int j=0;j<2;j++) {
System.out.println(Thread.currentThread().getName()+"\t"+j);
}
}
});
}
ex.shutdown();
}
}