代碼使用 Java 8:
public class MustDeadLock {
private static final Object obj1 = new Object();
private static final Object obj2 = new Object();
public static void main(String[] args) {
mockDeadLock();
}
public static void mockDeadLock() {
CompletableFuture cf1 = CompletableFuture.runAsync(() -> {
synchronized (obj1) {
System.out.println("thread A got lock: obj1");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("thread A ready to get the rest lock");
synchronized (obj2) {
System.out.println("thread A got all locks");
}
}
});
CompletableFuture cf2 = CompletableFuture.runAsync(() -> {
synchronized (obj2) {
System.out.println("thread B got lock: obj2");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("thread B ready to get the rest lock");
synchronized (obj1) {
System.out.println("thread B got all locks");
}
}
});
CompletableFuture.allOf(cf1, cf2);
System.out.println("program ready to terminate");
}
}
我想知道為什么
System.out.println("thread A ready to get the rest lock");
和
System.out.println("thread B ready to get the rest lock");)
不要被執行。
為什么它只列印:
thread B got lock: obj2
thread A got lock: obj1
program ready to terminate
然后終止程式而不是阻塞?
uj5u.com熱心網友回復:
僅僅因為您的主執行緒在其他執行緒處于休眠狀態時繼續執行。
如果您想在繼續執行之前等待這些執行緒完成,您可以在方法結束之前加入它們:
// rest of the program
cf1.join();
cf2.join();
System.out.println("program ready to terminate");
這將列印:
thread B got lock: obj2
thread A got lock: obj1
thread B ready to get the rest lock
thread A ready to get the rest lock
這將產生死鎖,程式永遠不會終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/517040.html
標籤:爪哇多线程
