可以用interrupt()方法中断线程,而线程是否已经中断则用Thread.currentThread().isInterrupted()方法返回true/false判断:
1、线程start()后马上调用interrupt(),在进入run()时中断标志已经被set on;
2、在处理sleep()可能抛出的InterruptedException时,再次中断线程即可成功中断;
3、注意interrupt()方法是set on 中断标志的,interrupted()方法是判断后并清除中断标志的。
public class ThreadDemo extends Thread{
public static void main(String[] args){
try{
ThreadDemo thread = new ThreadDemo();
thread.start();
thread.sleep(100);
thread.interrupt(); //中断线程
thread.sleep(100);
thread.printStr();
thread.interrupt(); //第三次中断线程
thread.printStr();
thread.join();
}catch(InterruptedException e){
e.printStackTrace();
}
}
private void printStr(){
System.out.println("thread obj");
}
@Override
public void run() {
while(!Thread.currentThread().isInterrupted()) {
System.out.println("thread running");
try {
Thread.sleep(100);
}catch(InterruptedException e)
{
System.out.println("InterruptedException");
Thread.currentThread().interrupt(); //再次中断线程
}
}
System.out.println("thread interrupted");
}
}
运行结果:
thread running
InterruptedException
thread interrupted
thread obj
thread obj