[問題] 想請問lock的用法

看板java作者 (LaPass)時間10年前 (2015/05/29 11:53), 10年前編輯推噓2(209)
留言11則, 3人參與, 最新討論串1/1
想做到類似 BlockingQueue 的功能 請問該怎麼做? 例如 void start(Item t){ //解除下面的get()的 block } void run(){ while(true){ //block 這條 thread dosomething(); } } 感覺起來要用lock,但是又怕start的時候被 block住 我希望只有在run()被block的狀況下才解除block 其他狀況什麼都不做 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 125.227.87.115 ※ 文章網址: https://www.ptt.cc/bbs/java/M.1432871603.A.022.html

05/29 14:02, , 1F
Object.wait/notify
05/29 14:02, 1F

05/29 15:03, , 2F
試不出來,叫了notify notifyAll 可是wait都沒醒
05/29 15:03, 2F
private class DrawRunnable implements Runnable{ void update(){ last=System.currentTimeMillis(); synchronized (this){ notifyAll(); } } public void run() { while (run) { try { //dosomething synchronized (this) { wait(); // <= 卡在這裡,其他執行序叫了update也沒醒 } Log.d("F23ko", "DrawRunnable STEP UNLOCK"); } catch (InterruptedException e) { } } } } ※ 編輯: LaPass (125.227.87.115), 05/29/2015 15:10:55

05/29 15:15, , 3F
是在android上,不過這應該不會有影響才對
05/29 15:15, 3F

05/29 15:22, , 4F
用 thread.interrupt() 可以叫的醒,不過覺得用那種方式去
05/29 15:22, 4F

05/29 15:22, , 5F
叫執行序不太好...
05/29 15:22, 5F

05/29 15:26, , 6F
因為可能作到一半(非block狀態下)被打斷
05/29 15:26, 6F

05/29 17:25, , 7F
你兩個Thread拿到的this是一樣的嗎?
05/29 17:25, 7F

05/29 17:37, , 8F
如果兩條thread操作的DrawRunnable是同一個,這code
05/29 17:37, 8F

05/29 17:37, , 9F
看起來沒問題…orz
05/29 17:37, 9F

05/29 18:18, , 10F
我確認一下.....
05/29 18:18, 10F

05/29 19:22, , 11F
對不起,是我耍蠢了 m(_ _)m
05/29 19:22, 11F
文章代碼(AID): #1LP-Ap0Y (java)
文章代碼(AID): #1LP-Ap0Y (java)