可以看到我们上⾯的代码指定了:
- corePoolSize : 核⼼线程数为 5。
- maximumPoolSize :最⼤线程数 10
- keepAliveTime : 等待时间为 1L。
- unit : 等待时间的单位为 TimeUnit.SECONDS。
- workQueue :任务队列为 ArrayBlockingQueue ,并且容量为 100;
- handler :饱和策略为 CallerRunsPolicy 。
package com.nowcoder.community.练习;
import java.util.Date;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
*这是一个简单的Runable类,需要大约五秒来执行任务。
* @author 找花插的牛粪
*/
public class 线程池 implements Runnable {
private String command;
public 线程池(String command) {
this.command = command;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
"Start.Time=" + new Date());
processCommand();
System.out.println(Thread.currentThread().getName() +
"End.Time=" + new Date());
}
private void processCommand(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public String toString() {
return "线程池{" +
"command='" + command + '\'' +
'}';
}
}
class TestPoll{
/**
* @author 找花插的牛粪
* @param 线程测试
*/
private static final int CORE_POOL_SIZE = 5;
private static final int MAX_POOL_SIZE = 10;
private static final int QUEUE_CAPACITY = 100;
private static final Long KEEP_ALIVE_TIME = 1L;
public static void main(String[] args) {
//使⽤阿⾥巴巴推荐的创建线程池的⽅式
//通过ThreadPoolExecutor构造函数⾃定义参数创建
ThreadPoolExecutor threadPoolExecutor =new ThreadPoolExecutor(
CORE_POOL_SIZE,
MAX_POOL_SIZE,
KEEP_ALIVE_TIME,
TimeUnit.SECONDS,
new ArrayBlockingQueue<>(QUEUE_CAPACITY),
new ThreadPoolExecutor.CallerRunsPolicy()
);
for (int i = 0; i < 10; i++) {
//创建WorkerThread对象(WorkerThread类实现了Runnable 接⼝)
线程池 线程池=new 线程池(""+i);
threadPoolExecutor.execute(线程池);
}
//终止线程
threadPoolExecutor.shutdown();
//isTerminated:当调用shutdown()方法后,并且所有提交的任务完成后返回为true;
//isTerminated:当调用shutdownNow()方法后,成功停止后返回为true;
while(!threadPoolExecutor.isTerminated()){
}
System.out.println("Finished all threads");
}
}
《阿⾥巴巴Java开发⼿册》中强制线程池不允许使⽤ Executors 去创建,⽽是通过ThreadPoolExecutor 的⽅式,这样的处理⽅式让写的同学更加明确线程池的运⾏规则,规避资源耗尽的⻛险
线程池具体流程简介:
在这就举个栗子吧:
比如一个公司,有自己的核心员工(核心线程),和供给核心员工工作的需求池(阻塞队列),还有外包员工(非核心线程)。
当一个任务来临时,经理就判断,咱么公司的核心员工(核心线程)是不是闲着呢,如果闲着呢,就选个核心员工去干,当然如果核心员工都在忙碌的话,经理就先把工作放进需求池 (阻塞队列)里面,等值核心员工一点点去干,如果需求池都满了,经理就考虑选择咱们的外包员工 (非核心线程)去干,如果外包员工也都忙碌起来了,就执行公司的淘汰任务策略(饱和策略)。