java线程池知识总结(附上思维导图)
线程池的优点
线程池最大的好处就是减少每次启动、销毁线程的损耗 。
构造方法及参数意义
public ThreadPoolExecutor(int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue workQueue,
RejectedExecutionHandler handler)
- corePoolSize:允许核心线程的最大值
- maximumPoolSize:允许的最大线程数(核心+临时)
- keepAliveTime+unit:临时线程允许的最长的空闲时间,超过则销毁临时线程
- workQueue:传递任务的阻塞队列
- handler:handler:没有能力完成任务时的拒绝策略
- AbortPolicy:抛出一个 RejectedExecutionException 异常
- CallerRunsPolicy:由提交任务的线程执行任务
- DiscardOldestPolicy:丢弃队列中最早的任务
- DiscardPolicy:丢弃当前任务
执行流程
简单实现线程池
public class MyThreadPool {
private int nThreads; // 记录允许创建的最大线程数
private List<Thread> threads; // 工作线程
private BlockingQueue<Runnable> workQueue; // 任务阻塞队列
private static class Worker extends Thread {
private BlockingQueue<Runnable> workQueue;
Worker(BlockingQueue<Runnable> workQueue) {
this.workQueue = workQueue;
}
@Override
public void run() {
try {
while (true) {
Runnable target = workQueue.take();
target.run();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MyThreadPool(int nThreads) {
this.nThreads = nThreads;
workQueue = new LinkedBlockingQueue<>(); // 所有线程共享同一个阻塞队列对象
// 提交创建线程
threads = new ArrayList<>();
for (int i = 0; i < nThreads; i++) {
Thread thread = new Worker(workQueue);
thread.start();
threads.add(thread);
}
}
void execute(Runnable target) throws InterruptedException {
workQueue.put(target);
}
private static class Target implements Runnable {
private int n;
Target(int n) {
this.n = n;
}
@Override
public void run() {
System.out.println("执行第"+n+"个线程任务");
}
}
public static void main(String[] args) throws InterruptedException {
MyThreadPool pool=new MyThreadPool(10);
for (int i = 1; i <= 10; i++) {
pool.execute(new Target(i));
}
}
}
shutdown() VS shutdownNow()
- shutdown():不再接受任何新任务,有序执行完已提交的任务
- shutdownNow():不再接受新任务,尝试停止所有主动执行的任务,停止等待任务的处理,并返回正在等待执行的任务列表List。 从此方法返回时,这些任务将从任务队列中排除(删除)。