工具类 对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;
}
}