可控制停止的线程

2017-08-24  本文已影响111人  真胖大海

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

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

使用(伪代码)

//每隔一秒打印一个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;
    }
}


上一篇下一篇

猜你喜欢

热点阅读