被打断的线程在使用sleep,join, wait方法时候都能他受到InterruptedException打断信号抛出异常
打断sleep的线程
Thread t = new Thread(() -> {
while(true){
}
});
t.start();
try {
// 如果直接打断,可能还没有起来呢, 所以这里简单休眠一下
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.isInterrupted());
// 中断
t.interrupt();
System.out.println(t.isInterrupted());
打断join的线程
这里注意:因为join的是main线程,只能打断main线程,不是打断t线程
Thread t = new Thread(() -> {
while(true){
}
});
// 打断main线程
Thread main = Thread.currentThread();
Thread t2 = new Thread(() -> {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 因为join的是main线程, 所以这么是打断不了t线程的, 不像sleep,wait都是blocked的当前线程
// t.interrupt();
main.interrupt();
System.out.println("t线程被中断!");
});
t.start();
t2.start();
try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 不能直接在main线程中中断, 因为join的话,t线程没执行完不会执行到这里
// t.interrupt();
打断wait的线程
public class Test {
static final Object monitor = new Object();
public static void main(String[] args) {
Thread t = new Thread(() -> {
synchronized(monitor){
try {
monitor.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
t.interrupt();
}
}