stop()方法非常坑爹,早已不提倡使用,单纯使用interrupt()也不安全。
package thread;
public class StopThreadTest {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
TheadToStop th = new TheadToStop();
System.out.println(Thread.currentThread().getName() + " stating a new thread");
th.start();
Thread.sleep(300);
System.out.println(Thread.currentThread().getName() + " interrupt the thread");
th.interrupt();
Thread.sleep(400);
System.out.println(Thread.currentThread().getName() + " stop main");
}
}
class TheadToStop extends Thread{
//共享变量
private volatile boolean isStop = false;
@Override
public void interrupt(){
//调用interrupt之前,把isStop置为false
isStop = true;
super.interrupt();
}
@Override
public void run(){
System.out.println(Thread.currentThread().getName() + " is going to run");
// double check,检查stop的状态
while(!isStop){
System.out.println(Thread.currentThread().getName() + " is running");
try {
Thread.sleep(400);
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + " is interrupt");
}
}
System.out.println(Thread.currentThread().getName() + " is exiting");
}
}