一、线程池核心参数
juc中关于线程池的核心类ThreadPoolExecutor的类结构如图所示:
创建线程池的核心参数解读
1、corePoolSize
预创建线程,核心池的大小。在创建了线程池后,默认情况下,线程池中并没有任何线程,而是等待有任务到来才创建线程去执行任务,除非调用了prestartAllCoreThreads()或者prestartCoreThread()方法,从这2个方法的名字就可以看出,即在没有任务到来之前就创建corePoolSize个线程或者一个线程。默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务,当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中;
2、maximumPoolSize:
线程池最大线程数,这个参数也是一个非常重要的参数,它表示在线程池中最多能创建多少个线程,在队列满了之后,核心线程不够用的情况下,开始创建核心线程之外的线程;
3、keepAliveTime
表示线程没有任务执行时最多保持多久时间会终止。默认情况下,只有当线程池中的线程数大于corePoolSize时,keepAliveTime才会起作用,直到线程池中的线程数不大于corePoolSize,即当线程池中的线程数大于corePoolSize时,如果一个线程空闲的时间达到keepAliveTime,则会终止,直到线程池中的线程数不超过corePoolSize。但是如果调用了allowCoreThreadTimeOut(boolean)方法,在线程池中的线程数不大于corePoolSize时,keepAliveTime参数也会起作用,直到线程池中的线程数为0;
4、unit
参数keepAliveTime的时间单位
5、workQueue
一个阻塞队列,用来存储等待执行的任务,这个参数的选择也很重要,会对线程池的运行过程产生重大影响,一般来说,这里的阻塞队列有以下几种选择:ArrayBlockingQueue、LinkedBlockingQueue、SynchronousQueue。一般使用LinkedBlockingQueue和Synchronous,LinkedBlockingQueue(无界阻塞队列),队列最大值为Integer.MAX_VALUE。如果任务提交速度持续大余任务处理速度,会造成队列大量阻塞。因为队列很大,很有可能在拒绝策略前,内存溢出。
6、threadFactory
线程工厂,主要用来创建线程;
7、handler
表示当拒绝处理任务,有以下几种取值
二、创建线程池
1、juc内置线程池
juc包下的Executors类提供的静态方法,创建预定义的线程池
代码示例:
/**
* @author wuchengfeng
*/
public class ApplyMulit {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
public static void main(String[] args) {
newMyFixThreadPool();
}
/**
* jdk自带的线程池创建方式
* Executors
*/
private static void newMyFixThreadPool() {
ExecutorService executorService = Executors.newFixedThreadPool(4);
MyRunnable myRunnable = new MyRunnable("AAAA");
MyRunnable myRunnable1 = new MyRunnable("BBBB");
MyRunnable myRunnable2 = new MyRunnable("CCCC");
MyRunnable myRunnable3 = new MyRunnable("DDDD");
for (int i = 0; i < 10; i++) {
System.out.println("#########################" + i);
executorService.execute(myRunnable);
executorService.execute(myRunnable1);
executorService.execute(myRunnable2);
executorService.execute(myRunnable3);
}
}
public static class MyRunnable implements Runnable {
private String threadName;
public String getThreadName() {
return threadName;
}
public void setThreadName(String threadName) {
this.threadName = threadName;
}
@Override
public String toString() {
return "MyRunnable=" + threadName;
}
MyRunnable(String threadName) {
this.threadName = threadName;
}
@Override
public void run() {
try {
System.out.println(sdf.format(new Date()) + "---create--" + this.toString());
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
总共12个线程,单个线程执行耗时3s,如果不使用线程池,串行执行的阻塞时间为36s;如果使用线程池,线程池并发处理4个线程,那么串行执行的阻塞时间为6s,大大提高了效率:
2、自定义线程池
public class MyThreadPool extends ThreadPoolExecutor {
private static volatile MyThreadPool myThreadPool;
private MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
}
/**
* 线程池但单实例
* 任务提交
* 方式1:
* Future<?> submit = myThreadPool.submit() 提交任务,先任务异常会被吞噬
*
* 方式2:
* Future<?> submit = myThreadPool.submit()
* submit.get() 会抛出异常
*
* 方式3:
* myThreadPool.execute() 会抛出异常
*
* @return
*/
public static MyThreadPool getPoolInstance(){
//线程总数的设置:对于cpu密集型的业务,可采用公式:cpu核心数x每核线程数+1;对于io密集型的的,而可采用公式:cpu核磁数x每核线程数x修正系数r(50<r<100)
if(myThreadPool==null){
synchronized (MyThreadPool.class){
if(myThreadPool==null){
///int cores = Runtime.getRuntime().availableProcessors();
OperatingSystemMXBean os = ManagementFactory.getOperatingSystemMXBean();
int cores = os.getAvailableProcessors();
myThreadPool = new MyThreadPool(cores/2,cores+1,3,TimeUnit.SECONDS,new ArrayBlockingQueue<>(1024));
myThreadPool.setRejectedExecutionHandler(new MyHandler());
myThreadPool.setThreadFactory(new MyThreadPool.ThreadFactoryBuilder());
}
}
}
return myThreadPool;
}
/**
* 线程池优雅关闭
*/
@Override
public void shutdown() {
if(myThreadPool!=null){
myThreadPool.shutdown();
try {
if(!myThreadPool.awaitTermination(5,TimeUnit.SECONDS)){
myThreadPool.shutdownNow();
if(!myThreadPool.awaitTermination(5,TimeUnit.SECONDS)){
System.out.println("pool is not terminate");
}
}
} catch (InterruptedException e) {
myThreadPool.shutdownNow();
Thread.currentThread().interrupt();
}
}
}
/***
* 处理任务提交异常
* @param r the runnable that has completed
* @param t the exception that caused termination, or null if
* execution completed normally
*/
@Override
protected void afterExecute(Runnable r, Throwable t) {
if(t!=null){
System.out.println("任务提交异常---"+t.getMessage());
}
if(t!=null && r instanceof Future<?>){
Future<?> future = (Future<?>) r;
if(future.isDone()){
try {
future.get();
} catch (InterruptedException e) {
System.out.println("InterruptedException任务提交异常---"+e.getMessage());
} catch (ExecutionException e) {
System.out.println("ExecutionException任务提交异常---"+e.getMessage());
Thread.currentThread().interrupt();
}
}
}
}
/**
* 自定义线程工厂
*/
public static class ThreadFactoryBuilder implements ThreadFactory {
private static final AtomicInteger THREAD_COUNT = new AtomicInteger(0);
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable);
thread.setName("cu_thread_"+THREAD_COUNT.getAndIncrement());
return thread;
}
}
/**
* 自定义拒绝策略
*/
public static class MyHandler extends ThreadPoolExecutor.CallerRunsPolicy {
@Override
public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
super.rejectedExecution(runnable, threadPoolExecutor);
showRejectPolicy(runnable, threadPoolExecutor);
}
void showRejectPolicy(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
System.out.println("***runnable=" + runnable.toString() + "###threadPoolExecutor=" + threadPoolExecutor.toString());
}
}
}
3、线程池的生命周期
Running:能接受新任务以及处理新添加的任务;
Shutdown:不能接受新任务,可以处理已经添加任务;
Stop:不接受新任务,不处理已经添加的任务,并且中断正在处理的任务;
Tidying: 所有的任务已经终止,ctl记录的“任务数量”为0,ctl负责记录线程的运行状态与活动的线程数量;
Terminated: 线程池彻底终止,则线程转化为terminated状态;