停止线程:
- 停止线程要注意的实现
- 我们停止一个线程一般都会配合一个变量去控制。
- 如果我们停止的是一个等待状态下的线程,那么需要配合 interrupt 方法去使用。
public class Demo9 extends Thread {
boolean flag = true;
public Demo9(String name){
super(name);
}
@Override
public synchronized void run() {
int i = 0;
while(flag){
try {
this.wait();
} catch (InterruptedException e) {
System.out.println("接收到了一个InterruptedException..");
}
System.out.println(Thread.currentThread().getName()+":"+ i);
i++;
}
}
public static void main(String[] args) {
Demo9 d = new Demo9("狗娃");
d.start();
for(int i = 0 ; i<100 ; i++){
if(i==80){
d.interrupt();
}
System.out.println(Thread.currentThread().getName()+":"+i);
}
}