美文网首页
可控制停止的线程

可控制停止的线程

作者: 真胖大海 | 来源:发表于2017-08-24 17:57 被阅读111次

    工具类 对Thread的封装,实现 可以停止无限循环的线程

    • 构造时传入Runnable continueRunnable
      continueRunnable为在无限循环里要执行的代码

    • setSleepTime(long sleepTime) 每隔sleepTime毫秒执行一次continueRunnable

    • start() 启动线程

    • setStop() 停止无限循环,退出线程

    此类设置成一旦关闭就不可以开启

    使用(伪代码)

    //每隔一秒打印一个1
      final CanStopLoopThread canStopLoopThread=new Thread(
        new Runable(){
            public void run(){
                print(1);
            }
        }
      );
      canStopLoopThread.setSleepTime(1000);
      canStopLoopThread.start();
      //canStopLoopThread.stop();需要停止时调用
    
    
    
    /**
     * Created  on 2017/7/20.
     *
     * @author xyb
     */
    
    public class CanStopLoopThread {
        private static final String TAG="CanStopLoopThread";
        private Thread thread;
        private volatile boolean stop = false;
        private long sleepTime=1000;
    
        public CanStopLoopThread(final Runnable continueRunnable) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        if (stop) {
                            return;
                        }
                        continueRunnable.run();
                        try {
                            Thread.sleep(sleepTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        }
    
        public void start() {
            thread.start();
        }
    
        public void setStop() {
            this.stop = true;
        }
    
        public void setSleepTime(long sleepTime) {
            this.sleepTime = sleepTime;
        }
    }
    
    
    

    相关文章

      网友评论

          本文标题:可控制停止的线程

          本文链接:https://www.haomeiwen.com/subject/pqwedxtx.html