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();
- }
-
- }
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|