职场文秘网

首页 > 心得体会 > 工作体会 / 正文

2023年java线程池框架解析方法(完整)

2023-03-07 19:30:11

Java对象实例的锁一共有四种状态:无锁,偏向锁,轻量锁和重量锁。原始脱离框架的并发应用大部分都需要手动完成加锁释放,最直接的就是使用synchronized和volatile关键字对某个对象或者下面是小编为大家整理的2023年java线程池框架解析方法(完整),供大家参考。

2023年java线程池框架解析方法(完整)

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

  一、线程池结构图

  二、示例

  定义线程接口

  6public class MyThread extends Thread @Overridepublicvoid run System.out.printlnThread.currentThread.getName + "正在执行";

  1:newSingleThreadExecutor

  10ExecutorService pool = Executors. newSingleThreadExecutor;Thread t1 = new MyThread;Thread t2 = new MyThread;Thread t3 = new MyThread;//将线程放入池中进行执行pool.executet1;pool.executet2;pool.executet3;//关闭线程池pool.shutdown;

  输入结果:

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

  2:newFixedThreadPool

  13ExecutorService pool = Executors.newFixedThreadPool3;Thread t1 = new MyThread;Thread t2 = new MyThread;Thread t3 = new MyThread;Thread t4 = new MyThread;Thread t5 = new MyThread;//将线程放入池中进行执行pool.executet1;pool.executet2;pool.executet3;pool.executet4;pool.executet5;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.executet1;pool.executet2;pool.executet3;pool.executet4;pool.executet5;//关闭线程池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.newScheduledThreadPool2;pool.scheduleAtFixedRatenew Runnable //每隔一段时间就触发异常 @Override public void run //throw new RuntimeException; System.out.println"================"; , 1000, 2000, TimeUnit.MILLISECONDS;pool.scheduleAtFixedRatenew Runnable //每隔一段时间打印系统时间,证明两者是互不影响的 @Override public void run System.out.println"+++++++++++++++++"; , 1000, 2000, TimeUnit.MILLISECONDS

Tags: 线程   框架   解析  

搜索
网站分类
标签列表