java线程池框架解析方法
Java对象实例的锁一共有四种状态:无锁,偏向锁,轻量锁和重量锁。原始脱离框架的并发应用大部分都需要手动完成加锁释放,最直接的就是使用synchronized和volatile关键字对某个对象或者代码块加锁从而限制每次访问的次数,从对象之间的竞争也可以实现到对象之间的'协作。但是这样手动实现出来的应用不仅耗费时间而且性能表现往往又有待提升。
一、线程池结构图
二、示例
定义线程接口
6public class MyThread extends Thread {@Overridepublicvoid run() {System.out.println(Thread.currentThread().getName() + "正在执行");}}
1:newSingleThreadExecutor
10ExecutorService pool = Executors. newSingleThreadExecutor();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();//将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);//关闭线程池pool.shutdown();
输入结果:
3pool-1-thread-1正在执行pool-1-thread-1正在执行pool-1-thread-1正在执行
2:newFixedThreadPool
13ExecutorService pool = Executors.newFixedThreadPool(3);Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.execute(t5);pool.shutdown();
输入结果:
4pool-1-thread-1正在执行pool-1-thread-2正在执行pool-1-thread-1正在执行pool-1-thread-2正在执行
3 :newCachedThreadPool
14ExecutorService pool = Executors.newCachedThreadPool();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//将线程放入池中进行执行pool.execute(t1);pool.execute(t2);pool.execute(t3);pool.execute(t4);pool.execute(t5);//关闭线程池pool.shutdown();
输入结果:
5pool-1-thread-2正在执行pool-1-thread-4正在执行pool-1-thread-3正在执行pool-1-thread-1正在执行pool-1-thread-5正在执行
4 :ScheduledThreadPoolExecutor
14ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);pool.scheduleAtFixedRate(new Runnable() {//每隔一段时间就触发异常 @Override public void run() { //throw new RuntimeException(); System.out.println("================"); }}, 1000, 2000, TimeUnit.MILLISECONDS);pool.scheduleAtFixedRate(new Runnable() {//每隔一段时间打印系统时间,证明两者是互不影响的 @Override public void run() { System.out.println("+++++++++++++++++"); }}, 1000, 2000, TimeUnit.MILLISECONDS)
【java线程池框架解析方法】相关文章: