炎热的夏天,来一杯卡布奇诺,解解乏...
线程池应用场景:银行叫号排队
1.三个柜台办理业务,来了六个人,其中三个人办理业务,另外三个人在等待区等待。
2.如果又来了一个人,一共七个人,那么,4号窗口营业,等待区中随机一名去办理,新来的一名到等待区。
3.如果只是来了三个人,那么线程池机制检测,4、5号窗口就关闭。
4.柜台和等待区都满了,那么新来的人就回去,不办理业务了。
上代码
public class Test {
public static void main(String[] args) {
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 1L, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());
for (int i = 0; i< 9; i++){
threadPoolExecutor.execute(()->{
System.out.println(Thread.currentThread().getName() + "===>办理业务");
});
}
threadPoolExecutor.shutdown();
}
}
看一下源码,new ThreadPoolExecutor的参数是什么意思
//corePoolSize 核心线程数
//maximumPoolSize 最大线程数
//keepAliveTime 存活时间
//unit 时间 1秒没有就下班
//BlockingQueue<Runnable> workQueue 等待队列
//ThreadFactory threadFactory, 线程工厂
//RejectedExecutionHandler handler 拒绝策略(抛异常)
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue,
ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException();
if (workQueue == null || threadFactory == null || handler == null)
throw new NullPointerException();
this.acc = System.getSecurityManager() == null ?
null :
AccessController.getContext();
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
ok,今天的博客就到这里。