让线程实现暂停,重新启动,停止

public class BaseThread extends Thread{
        private final static Logger logger = Logger.getLogger(BaseThread.class);

        /**
         * isDead:是否杀死线程
         */
        private boolean isDead = false;
        
        /**
         * isStop:是否停止
         */
        private boolean isStop = false;
        
        /**
         * isRun:是否已开始执行
         */
        private boolean isRun = false;
        
        /**
         * isWait:是否处于等待
         */
        private boolean isSleep = false;
        
        public BaseThread() {
                super();
                this.setDaemon(false);//设置为非守护线程
                logger.info("线程:["+this.getId()+"] 被创建");
        }
        
        public BaseThread(String threadName) {
                super(threadName);
                this.setDaemon(false);//设置为非守护线程
                logger.info("线程:["+threadName+"-"+this.getId()+"] 被创建");
        }

        /**
         *

Title: run

*

Description:JDK线程类自带方法

* @param @return 设定文件 * @return boolean 返回类型 * @throws */ public void run() { this.isRun = true; while(!isDead){ while(true){ if(!isStop){ if(preConditions())execute(); }else{ break; } sleep(256);//缓解CPU压力,即唤醒线程需要至多256ms } } isRun = false; logger.info("线程:[" + this.getName() +"-"+this.getId()+ "] 消亡"); } /** *

Title: preConditions

*

Description:执行体前置条件

* @param @return 设定文件 * @return boolean 返回类型 * @throws */ protected boolean preConditions(){ return true; } /** *

Title: execute

*

Description:线程执行体

* @param 设定文件 * @return void 返回类型 * @throws */ protected void execute(){ } /** *

Title: kill

*

Description:结束线程

* @param 设定文件 * @return void 返回类型 * @throws */ public void kill(){ this.isStop = true; this.isDead = true; this.isRun = false; logger.info("线程:["+this.getName()+"-"+this.getId()+"] 被终止"); } /** *

Title: halt

*

Description:暂停进程,非休眠

* @param 设定文件 * @return void 返回类型 * @throws */ public void halt(){ this.isStop = true; logger.info("线程:["+this.getName()+"-"+this.getId()+"] 被暂停"); } /** *

Title: reStart

*

Description:重新执行线程

* @param 设定文件 * @return void 返回类型 * @throws */ public void reStart(){ this.isStop = false; logger.info("线程:["+this.getName()+"-"+this.getId()+"] 被重新执行"); } /** *

Title: isRun

*

Description:是否处于执行态

* @param @return 设定文件 * @return boolean 返回类型 * @throws */ public boolean isRun() { return isRun; } /** *

Title: isSleep

*

Description:是否处于休眠态

* @param @return 设定文件 * @return boolean 返回类型 * @throws */ public boolean isSleep() { return isSleep; } public boolean isDead(){ return isDead; } /** *

Title: sleep

*

Description:休眠线程

* @param @param millis * @param @throws InterruptedException 设定文件 * @return void 返回类型 * @throws */ public void sleep(int millis){ isSleep = true; try { Thread.sleep(millis); this.sleepTime += millis; if(notifyPreConditions())notifyObs(); } catch (InterruptedException e) { e.printStackTrace(); } isSleep = false; }

你可能感兴趣的:(让线程实现暂停,重新启动,停止)