工具類 對Thread的封裝,實(shí)現(xiàn) 可以停止無限循環(huán)的線程
構(gòu)造時傳入Runnable continueRunnable
continueRunnable為在無限循環(huán)里要執(zhí)行的代碼setSleepTime(long sleepTime) 每隔sleepTime毫秒執(zhí)行一次continueRunnable
start() 啟動線程
setStop() 停止無限循環(huán),退出線程
此類設(shè)置成一旦關(guān)閉就不可以開啟
使用(偽代碼)
//每隔一秒打印一個1
final CanStopLoopThread canStopLoopThread=new Thread(
new Runable(){
public void run(){
print(1);
}
}
);
canStopLoopThread.setSleepTime(1000);
canStopLoopThread.start();
//canStopLoopThread.stop();需要停止時調(diào)用
/**
* 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;
}
}