通知终止
场景:在主线程中启动子线程,如何让主线程通知到子线程,从而让子线程终止
public class StopThread {
public static void main(String[] args) throws InterruptedException {
Thread1 thread1 = new Thread1();
thread1.start();
System.out.println("主线程开始休眠10s");
Thread.sleep(10*1000);
thread1.setToop(false);
}
}
class Thread1 extends Thread{
private static int num = 0;
private Boolean toop = true;
@Override
public void run() {
while (toop){
System.out.println("线程"+Thread.currentThread().getName()+"在运行中:"+(num++));
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setToop(Boolean toop){
this.toop=toop;
}
}
网友评论