停止线程
- 不推荐使用JDK提供的stop()、destroy()方法(已废弃)
- 推荐线程自己停下来(有停下来的条件)
- 建议使用一个标志位作为终止变量。例当
flag=false
时,终止线程运行。
代码演示,使用标志位停止线程运行:
- 设置一个标志位
- 设置一个公开的方法停止线程,转换标志位
//1.建议线程正常停止 --》 利用次数,不建议死循环
//2.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{
// 1.设置一个标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("测试线程正在运行。。。"+i+++"。。。");
}
}
// 2.设置一个公开的方法停止线程,转换标志位
public void stopTread(){
this.flag = false;
}
}
测试:
public class Test {
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i <= 1000; i++) {
if (i==800){
//调用stop方法,切换标志位,让停止线程
testStop.stopTread();
System.out.println("线程停止。。。");
}
System.out.println("main线程正在运行。。。"+i+"。。。");
}
}
}
运行结果:
main
线程中运行到i=800
时,通过使用类TestStop
的公开方法stopTread()
停止了“测试线程”的运行,后边只有main
线程在运行直到i=1000
时main
线程也停止运行。
...
main线程正在运行。。。717。。。
测试线程正在运行。。。10157。。。
测试线程正在运行。。。10158。。。
...
main线程正在运行。。。799。。。
线程停止。。。
main线程正在运行。。。800。。。
main线程正在运行。。。801。。。
...
main线程正在运行。。。1000。。。
Process finished with exit code 0