package thread_;
public class ThreadExit {
public static void main(String[] args) throws InterruptedException {
T t = new T();
t.start();
//希望main线程终止线程t,必须修改loop变量 --> 通知方式
System.out.println("主线程休眠5s");
Thread.sleep(5*1000);//主线程休眠5s再去终止线程t。与此同时,线程t也在运行。主线程退出不代表子线程一定退出
t.setLoop(false);
}
}
class T extends Thread{
private Boolean loop = true;//设置控制变量
@Override
public void run() {
while(loop){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("每隔50ms输出");
}
}
public void setLoop(Boolean loop) {//因为私有,所以设置set方法
this.loop = loop;
}
}
02-23
1486
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-01
2902
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)