0%

停止线程

停止线程

  • 不推荐使用JDK提供的stop()、destroy()方法(已废弃)
  • 推荐线程自己停下来(有停下来的条件)
  • 建议使用一个标志位进行终止变量。例当flag=false时,终止线程运行。

代码演示,使用标志位停止线程运行:

  1. 设置一个标志位
  2. 设置一个公开的方法停止线程,转换标志位
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//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;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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=1000main线程也停止运行。

1
2
3
4
5
6
7
8
9
10
11
12
13
...
main线程正在运行。。。717。。。
测试线程正在运行。。。10157。。。
测试线程正在运行。。。10158。。。
...
main线程正在运行。。。799。。。
线程停止。。。
main线程正在运行。。。800。。。
main线程正在运行。。。801。。。
...
main线程正在运行。。。1000。。。

Process finished with exit code 0
若图片不能正常显示,请在浏览器中打开

欢迎关注我的其它发布渠道