ThreadFactory threadFactory,
RejectedExecutionHandler handler) {
if (corePoolSize < 0 ||
maximumPoolSize <= 0 ||
maximumPoolSize < corePoolSize ||
keepAliveTime < 0)
throw new IllegalArgumentException;
if (workQueue == || threadFactory == || handler == )
throw new PointerException;
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.workQueue = workQueue;
this.keepAliveTime = unit.toNanos(keepAliveTime);
this.threadFactory = threadFactory;
this.handler = handler;
}
参数说明如下:
- corePoolSize:线程池的核心线程数,即便线程池里没有任何任务,也会有corePoolSize个线程在候着等任务 。
- maximumPoolSize:最大线程数,不管提交多少任务,线程池里最多工作线程数就是maximumPoolSize 。
- keepAliveTime:线程的存活时间 。当线程池里的线程数大于corePoolSize时,如果等了keepAliveTime时长还没有任务可执行,则线程退出 。
- Unit:这个用来指定keepAliveTime的单位,比如秒:TimeUnit.SECONDS 。
- 【java线程技术分享,java多线程技术点】BlockingQueue:一个阻塞队列,提交的任务将会被放到这个队列里 。
- threadFactory:线程工厂,用来创建线程,主要是为了给线程起名字,默认工厂的线程名字:pool-1-thread-3 。
- handler:拒绝策略,当线程池里线程被耗尽,且队列也满了的时候会调用 。
对于BlockingQueue个人感觉还需要单独拿出来说一下 。
BlockingQueue:阻塞队列,有先进先出(注重公平性)和先进后出(注重时效性)两种,常见的有两种阻塞队列:ArrayBlockingQueue和LinkedBlockingQueue
队列的数据结构大致如图:

文章插图
队列一端进入,一端输出 。而当队列满时,阻塞 。BlockingQueue核心方法:1. 放入数据put2. 获取数据take 。常见的两种Queue:
2.2.2 ArrayBlockingQueue
基于数组实现,在ArrayBlockingQueue内部,维护了一个定长数组,以便缓存队列中的数据对象,这是一个常用的阻塞队列,除了一个定长数组外,ArrayBlockingQueue内部还保存着两个整形变量,分别标识着队列的头部和尾部在数组中的位置 。
一段代码来验证一下:
package map;
import java.util.concurrent.*;
public class MyTestMap {
// 定义阻塞队列大小
private static final int maxSize = 5;
public static void main(String[] args){
ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<Integer>(maxSize);
new Thread(new Productor(queue)).start;
new Thread(new Customer(queue)).start;
}
}
class Customer implements Runnable {
private BlockingQueue<Integer> queue;
Customer(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run {
this.cusume;
}
private void cusume {
while (true) {
try {
int count = (int) queue.take;
System.out.println("customer正在消费第" + count + "个商品===");
// 只是为了方便观察输出结果
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace;
}
}
}
}
class Productor implements Runnable {
private BlockingQueue<Integer> queue;
private int count = 1;
Productor(BlockingQueue<Integer> queue) {
this.queue = queue;
}
@Override
public void run {
this.product;
}
private void product {
while (true) {
try {
queue.put(count);
System.out.println("生产者正在生产第" + count + "个商品");
count++;
} catch (InterruptedException e) {
e.printStackTrace;
}
}
}
}
//输出如下
/**
生产者正在生产第1个商品
生产者正在生产第2个商品
推荐阅读
- rar解压工具哪个好 免费rar解压软件哪个好
- 忘记手机指纹解锁数字密码怎么处理掉
- 该怎样才能发表微博,为什么发的微博无法显示
- 电视机网络版和电视版有什么区别
- hwlal00是什么手机,华为hwl一al00是什么型号
- 影视大全该怎样才可以离线缓存
- 怎么给标注尺寸,ps怎么给中的物品标注尺寸大小
- 进口车查询是哪个网站,进口车从玻璃上怎么看是哪年款
- 黑云翻墨未遮山的下一句,黑云翻墨未遮山描绘的画面是什么?
