// 新建一个无数量限制的阻塞队列,用于存放已提交未 执行的任务
// 其实就是new LinkedBlockingQueue(Integer.MAX_VALUE);
BlockingQueue workQueue = new LinkedBlockingQueue();
// 新建一个线程池实例,最小线程数为5,最大线程数为10,线程
空闲
10秒超时
ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(5, 10, 10,
TimeUnit.SECONDS, workQueue);
// 提交100个任务
int size = 100;
// 使用计数器来阻塞主线程继续执行
final CountDownLatch countDownLatch = new CountDownLatch(size);
for (int i = 0; i < size; i++) {
// 提交任务
poolExecutor.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
countDownLatch.countDown(); // 减少计数器的值,每次减1
} catch (InterruptedException e) {
}
}
});
// 线程池里面有一个任务队列:workQueue,线程池里面的线程数量:0-->最小线程数-->最大线程数-->最小线程数
// 线程池里面的空闲线程会到任务队列取任务进行执行,直到所有的任务执行完为止
}
// 阻塞主线程,计数器的值为0时,释放,即上面的所有的任务都已经执行完了
countDownLatch.await();
System.out.println("workQueue.size() = " + workQueue.size());