结论: 已经获取到锁的能被中断,正在等待锁的不能被中断。
如:
public class Main {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
synchronized (Main.class) {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("Thread A interrupted");
}
}
}, "A");
thread.start();
thread.interrupt();
}
}
运行结果:
这里线程 A 获取到锁后被中断了。
又如:
public class Main {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
synchronized (Main.class) {
System.out.println("Thread A get lock");
}
});
synchronized (Main.class) {
thread.start();
thread.interrupt();
thread.join();
}
}
}
线程 A 会一直处于等待状态,并不会被中断。
版权声明:本文为z_s_b_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。