2 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超9個(gè)贊
當(dāng)線程同時(shí)接收到中斷和通知時(shí),行為可能會(huì)有所不同。
請(qǐng)參考https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.2.3
信用 - 并發(fā)興趣郵件列表上的 Alex Otenko

TA貢獻(xiàn)1810條經(jīng)驗(yàn) 獲得超5個(gè)贊
因?yàn)橹匦屡判?。在正常終止編譯器重新排序指令中斷和通知中,中斷在工作線程上調(diào)用并且沒有中斷異常拋出。嘗試通過讀取 volatile 變量來(lái)禁止重新排序,您總是會(huì)遇到異常中斷。
public class WaitNotifyAll {
private static volatile Object resourceA = new Object();
public static void main(String[] args) throws Exception {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
try {
System.out.println("threadA begin wait");
resourceA.wait();
System.out.println("threadA end wait");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread threaB = new Thread(new Runnable() {
@Override
public void run() {
synchronized (resourceA) {
System.out.println("threadC begin notify");
threadA.interrupt();
System.out.print(resourceA);
resourceA.notify();
}
}
});
threadA.start();
Thread.sleep(1000);
threaB.start();
System.out.println("main over");
}
}
添加回答
舉報(bào)