[問題] 先notify再wait是否可以跳過wait

看板java作者 (光波記憶)時間13年前 (2012/08/24 23:29), 編輯推噓0(004)
留言4則, 3人參與, 最新討論串1/1
小弟是從vc轉過來學java的 所以這問題可能有點奇怪 就是是否能先執行notify後 再遇到wait時就跳過 (類似vc裡面setevent和waitforsingleobject的情況) 測試碼如下,謝謝。 先開一個thread執行notify 自己sleep 3秒再wait 但無法結束程式 是否要用另外一個變數去存有沒有notify過呢 感謝。 ---------------------------------------------- public class NotifyTest { public static Object g_obj = null; public static void main(String[] args) { g_obj = new Object(); notifyThread nt = new notifyThread(); System.out.println("Sleep..."); try { Thread.sleep(3000); } catch (InterruptedException e) { } System.out.println("Wait..."); synchronized (g_obj) { try { g_obj.wait(); } catch (InterruptedException e) { } } System.out.println("End..."); } private static class notifyThread extends Thread{ notifyThread() { start(); } public void run() { synchronized (g_obj) { g_obj.notifyAll(); System.out.println("Notify..."); } } } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.254.2.140

08/25 00:32, , 1F
vc 不是語言....
08/25 00:32, 1F

08/25 12:10, , 2F
原po似乎想要counting semaphore.notify/wait比較像binary
08/25 12:10, 2F

08/25 12:12, , 3F
semaphore. 可直接使用java的semaphore
08/25 12:12, 3F

09/05 08:45, , 4F
增加 boolean isDone, 在同步區塊變更就可以了
09/05 08:45, 4F
文章代碼(AID): #1GDvtale (java)