How the thread stops
1. It is recommended that the thread stop normally ----- "Utilization times, infinite loops are not recommended
. 2. It is recommended to use the flag ----- "Set a flag bit
. 3. Do not use stop or destroy methods that are outdated or not recommended by jdk
*Here we use the flag bit: stop the child thread when the main thread reaches the 90th time
//测试stop
//1.建议线程正常停止-----》利用次数,不建议死循环
//2.建议使用标志位-----》设置一个标志为
//3.不要使用stop或者destroy等过时或者jdk不建议的方法
public class TextThread5 implements Runnable {
//设置一个标志位
private boolean flag=true;
@Override
public void run() {
int i=0;
while (flag){
System.out.println("子线程"+i++);
}
}
//设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag=false;
}
public static void main(String[] args) {
TextThread5 textThread5=new TextThread5();
new Thread(textThread5).start();
for (int i = 0; i < 100; i++) {
System.out.println("main线程"+i);
if (i==90){
//调用stop方法切换标识符,让线程停止
textThread5.stop();
System.out.println("子线程该停止了");
}
}
}
}
effect: