public class ThreadInterrupt {
public static void main(String[] args) throws InterruptedException {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
// t2.start();
Thread.sleep(200);
System.out.println("t1被中断");
t1.interrupt();
Thread.sleep(2000000);
}
}
class Thread1 extends Thread{
@Override
public void run() {
int i=0;
while(true){
System.out.println(Thread.currentThread().isInterrupted());
if(!Thread.currentThread().isInterrupted()){
System.out.println("线程:"+Thread.currentThread().getName()+"run..."+i);
i++;
}else{
System.out.println(Thread.currentThread().getName()+"--EXIT");
break;
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.out.println("线程被中断.."+Thread.currentThread().getName());
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}
class Thread2 extends Thread{
@Override
public void run() {
int i=0;
while(true){
if(!Thread.currentThread().isInterrupted()){
System.out.println("线程"+Thread.currentThread().getName()+"run.."+"aa");
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
System.out.println("线程被中断.."+Thread.currentThread().getName());
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
}
因为在wait或者在sleep的时候也可以随时被中断的,即要随时对interrupt做出相应;当程序在sleep的过程中被中断,那么程序会跳到catch中去,抛出中断异常;当线程抛出异常中断异常的时候会清空中断标志位,所以在catch中要再次设置中断标志位,如果不设置的话程序仍然会继续执行,不会被真正的中断