public class MyThreadPoolDemo {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newFixedThreadPool(5); //一池子5个处理线程
//ExecutorService threadPool = Executors.newSingleThreadExecutor(); //一池子1个处理线程
ExecutorService threadPool = Executors.newCachedThreadPool(); //一池子n个处理线程
try{
//模拟10个用户的请求,由那5个人来半
//我,要密码挂失
//我,信用卡申请
//我,注销用户等等等等业务不一样的请求
for (int i = 0; i < 10; i++) {
//这10个用户的请求,都由这个线程池(threadPool)来处理
threadPool.execute(() ->{
System.out.println(Thread.currentThread().getName()+"\t 办理业务");
});
//暂停一会儿线程
// try{
// TimeUnit.MILLISECONDS.sleep(200);
// }catch (InterruptedException e){
// e.printStackTrace();
// }
}
}
catch (Exception e){
e.printStackTrace();
}finally {
threadPool.shutdown();
}
}
}
固定5个:
newCachedThreadPool()可扩容的:没睡之前:太快了,需要8个线程。VS sleep后,一个线程处理得来
一、请说出线程池底层的源码和5大参数?