持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第27天,点击查看活动详情
线程池3种队列结合线程池最大线程数的关系
看出ArrayBlockingQueue源码, ArrayBlockingQueue构造方法代码如下:
public ArrayBlockingQueue(int capacity,boolean fair){
if(capacity <= 0){
throw new IllegalArgumentException();
}
this.items=new Object[capacity];
lock = new ReentrantLock(fair);
notEmpty = lock.newCondition();
notFull = lock.newCondition();
}
而LinkedBlockingDeque队列构造方法代码如下:
public LinkedBlockingDeque(int capacity){
if(capacity <= 0){
throw new IllegalArgumentException();
}
this.capacity=capacity;
}
看通过源码看出如果传入capacity值是<=0时是出现异常的。
当执行任务的数量大于ThreadPoolExecutor线程池的最大线程数时,在不同队列中会出现以下情况:
线程执行代码如下:
public class FirstRunnable implements Runnable {
@Override
public void run() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
try {
System.out.println(Thread.currentThread().getName() +" 开始时间:"+simpleDateFormat.format(new Date()));
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" 结束时间:"+simpleDateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行类代码如下:
public class LinkedBlockingQueueRun {
public static void main(String[] args) {
FirstRunnable firstRunnable = new FirstRunnable();
LinkedBlockingDeque<Runnable> linkedBlockingDeque = new LinkedBlockingDeque<Runnable>(2);
System.out.println("队列个数:"+linkedBlockingDeque.size());
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 5, TimeUnit.SECONDS, linkedBlockingDeque);
for (int i = 0; i < 5; i++) {
threadPoolExecutor.execute(firstRunnable);
}
System.out.println("线程池正在执行的任务个数:"+threadPoolExecutor.getPoolSize());
System.out.println("线程池使用的队列个数:"+linkedBlockingDeque.size());
}
}
运行结果如下:
队列个数:0
线程池正在执行的任务个数:3
线程池使用的队列个数:2
pool-1-thread-1 开始时间:14:53:52
pool-1-thread-3 开始时间:14:53:52
pool-1-thread-2 开始时间:14:53:52
pool-1-thread-2 结束时间:14:53:53
pool-1-thread-3 结束时间:14:53:53
pool-1-thread-1 结束时间:14:53:53
pool-1-thread-1 开始时间:14:53:53
pool-1-thread-3 开始时间:14:53:53
pool-1-thread-1 结束时间:14:53:54
pool-1-thread-3 结束时间:14:53:54
从运行结果看出线程池正在执行的线程的任务数为3,而队列存放的元素个数为2。