一、 线程池参数
二、线程执行流程
一般任务个数小于核心线程数先创建线程执行任务,大于核心线程数的任务会先安排在等待队列中,如果等待队列也满了的话,会先创建小于线程池线程总数的个数执行任务,如果队列满了之后还有其他任务则会执行拒绝策略。
线程执行流程图:
线程添加规则:
三、线程增加特点
newSchedualThreadPool支持定期和周期执行任务
四、线程数量设定
五、线程池的五个方法
shutdown、isShutdown、isTreminated、awaitTermination、shutdownNow
package threadpool;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ShutDown {
public static void main(String[] args) {
//这里ExecutorService是ThreadPoolExecutor的父类(父类引用指向子类对象)
ExecutorService executorService= Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
executorService.execute(new ShutDowntask());
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
//暴力关闭线程,正在执行的都中断,返回未执行的线程runnablelist
List<Runnable> runnableList = executorService.shutdownNow();
//isShutdown()判断线程池是否关闭
System.out.println(executorService.isShutdown());
//关闭线程池后再提交任务会拒绝。但会执行完之前的任务
executorService.shutdown();
System.out.println(executorService.isShutdown());
//判断是否结束执行任务
System.out.println(executorService.isTerminated());
//关闭至后再提交任务会拒绝
executorService.execute(new ShutDowntask());
}
}
class ShutDowntask implements Runnable{
@Override
public void run() {
try {
Thread.sleep(1500);
System.out.println(Thread.currentThread().getName());
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName()+"被中断了");
}
}
}
六、4种拒绝策略
Java-五种线程池,四种拒绝策略,三种阻塞队列
三种阻塞队列:
BlockingQueue<Runnable> workQueue = null;
workQueue = new ArrayBlockingQueue<>(5);//基于数组的先进先出队列,有界
workQueue = new LinkedBlockingQueue<>();//基于链表的先进先出队列,无界
workQueue = new SynchronousQueue<>();//无缓冲的等待队列,无界
四种拒绝策略:
RejectedExecutionHandler rejected = null;
rejected = new ThreadPoolExecutor.AbortPolicy();//默认,队列满了丢任务抛出异常
rejected = new ThreadPoolExecutor.DiscardPolicy();//队列满了丢任务不异常
rejected = new ThreadPoolExecutor.DiscardOldestPolicy();//将最早进入队列的任务删,之后再尝试加入队列
rejected = new ThreadPoolExecutor.CallerRunsPolicy();//如果添加到线程池失败,那么主线程(提交任务的线程)会自己去执行该任务
五种线程池:
ExecutorService threadPool = null;
threadPool = Executors.newCachedThreadPool();//有缓冲的线程池,线程数 JVM 控制
threadPool = Executors.newFixedThreadPool(3);//固定大小的线程池
threadPool = Executors.newScheduledThreadPool(2);
threadPool = Executors.newSingleThreadExecutor();//单线程的线程池,只有一个线程在工作
threadPool = new ThreadPoolExecutor();//默认线程池,可控制参数比较多
七、Executor家族
Executors工具类:提供方法