先看看java线程池的应用:通过工具类来构建一个线程池
ExecutorService executorService =Executors.newFixedThreadPool(4);
这里的 ExecutorService 就是一个线程池,通过线程池执行一个任务(Runnale 或者callbale)


在线程池中execute这个方法只能够执行Rannale的任务,执行完以后没有返回值,submit 方法可以执行Runnable he Callbale 任务,Callbale 任务执行完以后可以返回一个返回值
第一步先来看看线程池是怎么实现的:


现在可以开始分析线程池的的任务的提交了:


这里可以看看线程池的集成结构:

线程池通过一个int的高三位表示线程池的状态 低29位表示线程池中运行的线程数
即

通过上面执行任务的两个方法,我们会发现,这两个方法分别在不同的借口中,execute这个方法在最顶层的借口Executor中,而submit这个方法对应的在ExecutorService中.


下面分析关键的代码,这段代码是线程池实现的真真关键的部分:addWorker()这个方法是一个非常关键的代码


进入new Worker中发现worker是一个Runnable接口的对象


所以当worker对象添加成功以后,启动这个worker对象的线程的时候,执行的是worker对象中run方法


下面是getTask()方法的代码,工作队列中有任务这个while 循环就不会跳出当前线程一直在自旋执行任务

当线程池中的线程出现异常的时候。执行退出线程的流程:
先移除出现异常的线程,然后在添加一个新的线程。和timer不一样。timer只有一个线程,如果出现日常就没有线程执行任务了

submit()方法的分析;




shutdown()方法:


网友评论