class MyThread extends Thread {
private int counter = 0;
public void run() {
boolean done = false;
try{
Thread.sleep(10);
}catch(InterruptedException ie){
ie.printStackTrace();
return;
}
while (counter < 2000 &&!done) {
System.out.println(counter++ + " in thread isInterrupted() "+isInterrupted());
if(isInterrupted()==true){
try{
System.out.println("in thread after interrupted() "+isInterrupted());
sleep(100);
break;
}catch(InterruptedException ie){
ie.printStackTrace();
break;
}
}
}
}
}
public class Tes1 {
public static void main(String[] args) {
final MyThread t1 = new MyThread();
t1.start();
new Timer(true).schedule(new TimerTask() {
public void run() {
System.out.println("exec interrupt");
t1.interrupt();
System.out.println("in timer isInterrupted() "+t1.isInterrupted());
}
}, 20);
}
}
执行效果如下(每一次执行打印的都不一样,因为没有做线程同步):
...
1300 in thread isInterrupted() false
exec interrupt
in timer isInterrupted() true
1301 in thread isInterrupted() true
in thread after interrupted() true
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.wd.MyThread.run(Tes1.java:21)
还可能是这样:
...
1568 in thread isInterrupted() false
exec interrupt
in thread after interrupted() true
in timer isInterrupted() true
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.wd.MyThread.run(Tes1.java:21)
由于在sleep时执行了interrupt()所以会抛出异常。
如果把if(isInterrupted()==true)改成if(Thread.interrupted()==true)那么打印的结果就不同了,如下:
...
1582 in thread isInterrupted() false
exec interrupt
in timer isInterrupted() true
in thread after interrupted() false
还可能是这样:
...
1771 in thread isInterrupted() false
exec interrupt
in timer isInterrupted() true
1772 in thread isInterrupted() false
in thread after interrupted() false
也可能是这样:
...
476 in thread isInterrupted() false
in thread after interrupted() false
in timer isInterrupted() false