前言
JDK自带的stop不推荐使用,主要是线程不安全,可能会出现数据不同步,推荐使用自定义标识停止线程
示例代码
/**
* 停止线程
* @author terry
* @date 2018年2月25日
*/
public class ThreadStop implements Runnable{
private boolean flag = true;
@Override
public void run() {
while(flag){
System.out.println("该线程正在执行。。。");
}
}
public void stop() {
flag = false;
}
public static void main(String[] args) {
ThreadStop threadStop = new ThreadStop();
Thread thread = new Thread(threadStop);
thread.start();
int i = 0;
while (threadStop.flag) {
i++;
if (i == 5) {
threadStop.stop();
}
System.out.println("已执行:"+i+"次");
}
}
}
打印输出:
该线程正在执行。。。
该线程正在执行。。。
该线程正在执行。。。
该线程正在执行。。。
已执行:4次
该线程正在执行。。。
已执行:5次