之前使用过sleep来停止线程
我们这次使用别的方法来停止线程
//测试线程停止
//1.建议线程正常停止-----利用次数,不建议死循环
//2.建议使用标志位-------设置一个标志位
//3.不要使用stop,destroy等过时或JDK不建议的方法
public class TestStop implements Runnable{
//设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("the thread is runing...."+i++);
}
}
//设置一个停止方法
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 100; i++) {
System.out.println("this is main thread "+i);
if (i == 50){
testStop.stop();
System.out.println("the thread is stop.");
}
}
}
}
执行结果如下:
可以看到,当主线程到50时,我们更改了run线程的标志位 使它停止 此时run线程跑到了93的地方,主线程并没有停止,他要跑完了才不跑
使用标志位来停止线程,是一个比较建议的做法