线程属于稀缺资源,对于线程的创建规则,引用《阿里巴巴 java 手册》中的一条进行说明。
本篇从源码方面介绍threadpoolexecutor对象,并简要解析线程池工作原理。
首先threadpoolexecutor中定义了几个线程池状态常量。
// runstate is stored in the high-order bits private static final int running = -1 << count_bits; private static final int shutdown = 0 << count_bits; private static final int stop = 1 << count_bits; private static final int tidying = 2 << count_bits; private static final int terminated = 3 << count_bits;
看一下构造方法的参数
public threadpoolexecutor(int corepoolsize,int maximumpoolsize,long keepalivetime,timeunit unit,blockingqueue<runnable> workqueue, threadfactory threadfactory, rejectedexecutionhandler handler) { }
这里可以简单看下jdk中已有的4种饱和策略handler:
也可以自定义饱和策略,只需实现rejectedexecutionhandler接口。
再看一下jdk中的workqueue队列:
jdk提供了executors工厂类。这里面有几种实例化线程池的方法:
public static executorservice newfixedthreadpool(int nthreads) { return new threadpoolexecutor(nthreads, nthreads, 0l, timeunit.milliseconds, new linkedblockingqueue<runnable>()); }
指定了线程数,且corepoolsize == maximumpoolsize。
public static executorservice newcachedthreadpool() { return new threadpoolexecutor(0, integer.max_value, 60l, timeunit.seconds, new synchronousqueue<runnable>()); }
可缓存线程池。最大线程数达到integer.max_value。所以在使用该线程池时,一定要控制并发数,不然会创建很多线程,占用大量资源。
public static executorservice newsinglethreadexecutor() { return new finalizabledelegatedexecutorservice (new threadpoolexecutor(1, 1, 0l, timeunit.milliseconds, new linkedblockingqueue<runnable>())); }
只有一个线程的线程池,可以保证提交任务的顺序执行。
上面的实例方法都很方便,但是在开发中创建线程池时,最好不好使用executors类中的初始化方法。见《阿里巴巴 java 手册》:
最后看一下threadpoolexecutor执行任务的方法
public void execute(runnable command) { if (command == null) throw new nullpointerexception(); int c = ctl.get(); if (workercountof(c) < corepoolsize) { if (addworker(command, true)) return; c = ctl.get(); } if (isrunning(c) && workqueue.offer(command)) { int recheck = ctl.get(); if (! isrunning(recheck) && remove(command)) reject(command); else if (workercountof(recheck) == 0) addworker(null, false); } else if (!addworker(command, false)) reject(command); }
以一张简单的流程图描述上面的步骤:
如对本文有疑问, 点击进行留言回复!!
Mybatis PersistenceException异常:Error building SqlSession The error may exist in SQL Mapper Configur
MyBatis——动态SQL语句——if标签和where标签复合使用
网友评论