4 回答

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊
你這么寫只是個(gè)演示代碼,wait()和notify()是配合生產(chǎn)者-消費(fèi)者模型使用的。Android中的Volley框架也是使用這種原理來進(jìn)行多線程的并發(fā)調(diào)度。
不需要考慮JVM,你只需要考慮釋放時(shí)機(jī)和通知時(shí)間,建議參考我的這篇博客:Java并發(fā)寫作——wait-notify機(jī)制

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
引用jdk6中wait
方法的注釋
The current thread must own this object's monitor. The thread
releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to thenotify
method or thenotifyAll
method.
對(duì)應(yīng)到題主的代碼wait
調(diào)用后會(huì)釋放obj
對(duì)象的鎖。
另外,sleep
和yield
方法是不會(huì)釋放對(duì)象鎖的。

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超3個(gè)贊
你這代碼應(yīng)該會(huì)出現(xiàn)t2執(zhí)行完,t1不會(huì)執(zhí)行完的情況,這叫過早的notify,你應(yīng)該確保線程1總是先于2執(zhí)行才行。
添加回答
舉報(bào)