打断 sleep,wait,join 的线程
这几个方法都会让线程进入阻塞状态
打断 sleep 的线程, 会清空打断状态,以 sleep 为例
public static void test1() throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1");
t1.start();
Thread.sleep(500);
t1.interrupt();
System.out.println(" 打断状态: " + t1.isInterrupted());
}
输出
打断状态: false
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.weisoft.test.Test.lambda$0(Test.java:12)
at java.lang.Thread.run(Unknown Source)
打断正常运行的线程
打断正常运行的线程, 不会清空打断状态
public static void test2() throws InterruptedException {
Thread t2 = new Thread(() -> {
while (true) {
Thread current = Thread.currentThread();
boolean interrupted = current.isInterrupted();
if (interrupted) {
System.out.println(" 打断状态: " + interrupted);
break;
}
}
}, "t2");
t2.start();
Thread.sleep(500);
t2.interrupt();
}
输出
打断状态: true
模式之两阶段终止:
public class Test3 {
public static void main(String[] args) {
TwoPhaseTermination tpt = new TwoPhaseTermination();
tpt.start();
try {
Thread.sleep(3792);
} catch (InterruptedException e) {
e.printStackTrace();
}
tpt.stop();
}
}
class TwoPhaseTermination {
private Thread monitor;
public void start() {
monitor = new Thread(() -> {
while (true) {
Thread current = Thread.currentThread();
if (current.isInterrupted()) {
System.out.println("料理后事");
break;
}
try {
Thread.sleep(1000);
System.out.println("执行监控记录");
} catch (InterruptedException e) {
e.printStackTrace();
current.interrupt();
}
}
}) {
};
monitor.start();
}
public void stop() {
monitor.interrupt();
}
}
输出
执行监控记录
执行监控记录
执行监控记录
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
料理后事
at com.weisoft.test.TwoPhaseTermination.lambda$0(Test3.java:31)
at java.lang.Thread.run(Unknown Source)