2.要实现上面的线程池,就需要一个永不退出的线程与之配合。PThread就是一个这样的线程。它的主体部分是一个无限循环,该线程在手动关闭前永不结束,并一直等待新的任务到达。
- public class PThread extends Thread {
- //线程池
- private ThreadPool pool;
- //任务
- private Runnable target;
- private boolean isShutDown = false;
- private boolean isIdle = false; //是否闲置
- //构造函数
- public PThread(Runnable target,String name, ThreadPool pool){
- super(name);
- this.pool = pool;
- this.target = target;
- }
-
- public Runnable getTarget(){
- return target;
- }
-
- public boolean isIdle() {
- return isIdle;
- }
-
- @Override
- public void run() {
- //只要没有关闭,则一直不结束该线程
- while (!isShutDown){
- isIdle = false;
- if (target != null){
- //运行任务
- target.run();
- }
- try {
- //任务结束了,到闲置状态
- isIdle = true;
- pool.repool(this);
- synchronized (this){
- //线程空闲,等待新的任务到来
- wait();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- isIdle = false;
- }
- }
-
- public synchronized void setTarget(Runnable newTarget){
- target = newTarget;
- //设置了任务之后,通知run方法,开始执行这个任务
- notifyAll();
- }
-
- //关闭线程
- public synchronized void shutDown(){
- isShutDown = true;
- notifyAll();
- }
-
- }
(编辑:晋中站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|