hbf548

多看源码多读书

0%

线程停止

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//1.建议线程正常停止-----> 利用次数,不建议死循环
//2.建议使用标志位-----> 设置一个标志位
//3. 不要使用stop 或者 destory 等过时 或者 JDK不建议使用的方法

public class TestStop implements Runnable{

//设置一个标志位
private boolean flag = true;

@Override
public void run() {
while (flag){
System.out.println("run...Thread");
}
}

//2.设置一个公开的方法停止线程,转换标志位
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 < 1000; i++) {
System.out.println("main" + i);
if(i == 900){
//调用stop 方法切换标志位
testStop.stop();
System.out.println("线程停止了");
break;
}
}
}
}
image.png