线程停止的三种方式
1. 设置标志位(无法处理线程阻塞时的问题);
2. 调用Thread类提供的stop
方法强行关闭线程;
3. 通过Thread类提供的interrupt
方法
举例:设置标志位
class InterruptThread extends Thread{
private boolean flag = true;
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
int i =0;
while(flag){
i++;
System.out.println(Thread.currentThread().getName()+",i= "+i);
}
}
}
public class TestInterrupt {
public static void main(String[] args) throws InterruptedException {
InterruptThread t1 = new InterruptThread();
t1.start();
//子线程和主线程并发执行,为了看到效果,休眠1s
Thread.sleep(1000);
t1.setFlag(false