测试stop
1.建议线程正常停止:利用次数不建议死循环
2.建议使用标志位:设置一个标志位
3.不要使用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("running.......Thread"+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("main"+i);
if (i==90){
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
===================
输出
main0
main1
main2
main3
main4
main5
main6
running.......Thread0
main7
main8
main9
main10
main11
main12
main13
main14
main15
main16
main17
main18
main19
main20
main21
main22
main23
main24
main25
main26
main27
running.......Thread1
main28
running.......Thread2
main29
running.......Thread3
main30
main31
main32
main33
main34
main35
main36
running.......Thread4
main37
running.......Thread5
running.......Thread6
running.......Thread7
running.......Thread8
main38
running.......Thread9
main39
main40
main41
running.......Thread10
main42
running.......Thread11
main43
running.......Thread12
main44
running.......Thread13
running.......Thread14
running.......Thread15
running.......Thread16
running.......Thread17
running.......Thread18
running.......Thread19
running.......Thread20
running.......Thread21
running.......Thread22
main45
main46
main47
main48
main49
main50
main51
main52
main53
main54
main55
main56
main57
main58
main59
running.......Thread23
running.......Thread24
main60
main61
running.......Thread25
running.......Thread26
main62
running.......Thread27
running.......Thread28
running.......Thread29
running.......Thread30
running.......Thread31
running.......Thread32
running.......Thread33
running.......Thread34
running.......Thread35
running.......Thread36
main63
main64
main65
main66
main67
main68
main69
main70
main71
main72
main73
main74
main75
main76
main77
main78
main79
main80
main81
running.......Thread37
main82
running.......Thread38
main83
running.......Thread39
main84
main85
main86
main87
running.......Thread40
running.......Thread41
main88
running.......Thread42
running.......Thread43
running.......Thread44
running.......Thread45
running.......Thread46
running.......Thread47
running.......Thread48
main89
main90
running.......Thread49
线程该停止了
main91
main92
main93
main94
main95
main96
main97
main98
main99
Process finished with exit code 0