java线程池框架解析

使用Java中成型的框架来帮助我们开发并发应用即可以节省构建项目的时间,也可以提高应用的性能。以下是小编为大家搜索整理java线程池框架解析,希望能给大家带来帮助!更多精彩内容请及时关注我们应届毕业生考试网!

java线程池框架解析

Java对象实例的锁一共有四种状态:无锁,偏向锁,轻量锁和重量锁。原始脱离框架的并发应用大部分都需要手动完成加锁释放,最直接的就是使用synchronized和volatile关键字对某个对象或者代码块加锁从而限制每次访问的次数,从对象之间的竞争也可以实现到对象之间的协作。但是这样手动实现出来的`应用不仅耗费时间而且性能表现往往又有待提升。

  一、线程池结构图

  二、示例

定义线程接口

6public class MyThread extends Thread {@Overridepublicvoid run() {tln(entThread()ame() + "正在执行");}}

1:newSingleThreadExecutor

10ExecutorService pool = Executors. newSingleThreadExecutor();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);//关闭线程池down();

输入结果:

3pool-1-thread-1正在执行pool-1-thread-1正在执行pool-1-thread-1正在执行

2:newFixedThreadPool

13ExecutorService pool = ixedThreadPool(3);Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);down();

输入结果:

4pool-1-thread-1正在执行pool-1-thread-2正在执行pool-1-thread-1正在执行pool-1-thread-2正在执行

3 :newCachedThreadPool

14ExecutorService pool = achedThreadPool();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);//关闭线程池down();

输入结果:

5pool-1-thread-2正在执行pool-1-thread-4正在执行pool-1-thread-3正在执行pool-1-thread-1正在执行pool-1-thread-5正在执行

4 :ScheduledThreadPoolExecutor

14ScheduledExecutorService pool = cheduledThreadPool(2);duleAtFixedRate(new Runnable() {//每隔一段时间就触发异常 @Override public void run() { //throw new RuntimeException(); tln("================"); }}, 1000, 2000, ISECONDS);duleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的 @Override public void run() { tln("+++++++++++++++++"); }}, 1000, 2000, ISECONDS);

输入结果:

4================+++++++++++++++++++++++++++++++++++++++++++++++++++

  三、线程池核心参数

corePoolSize : 池中核心的线程数

maximumPoolSize : 池中允许的最大线程数。

keepAliveTime : 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。

unit : keepAliveTime 参数的时间单位。

workQueue : 执行前用于保持任务的队列。此队列仅保持由 execute方法提交的 Runnable任务。

threadFactory : 执行程序创建新线程时使用的工厂。

handler : 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。

ThreadPoolExecutor :Executors类的底层实现。

3.1 任务排队机制

SynchonousQueue: 同步队列,队列直接提交给线程执行而不保持它们,此时线程池通常是无界的

LinkedBlockingQueue: 无界对列,当线程池线程数达到最大数量时,新任务就会在队列中等待执行,可能会造成队列无限膨胀

ArrayBlockingQueue : 有界队列,有助于防止资源耗尽,一旦达到上限,可能会造成新任务丢失

注意:

newSingleThreadExecutor、newFixedThreadPool使用的是LinkedBlockingQueue

newCachedThreadPool 使用的是 SynchonousQueue

newScheduledThreadPool使用的是 DelayedWorkQueue

3.2 线程执行流程

3.3 线程大小确定:

cpu密集型: 尽量少开线程,最佳线程数 Ncpu+1

io密集型:多开线程,2Ncpu

混合型:根据情况而定,可以拆分成io密集和cou密集