作者LaPass (LaPass)
看板java
標題[問題] 想請問lock的用法
時間Fri May 29 11:53:19 2015
想做到類似 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://webptt.com/m.aspx?n=bbs/java/M.1432871603.A.022.html
1F:→ Chikei: Object.wait/notify 05/29 14:02
2F:→ LaPass: 試不出來,叫了notify notifyAll 可是wait都沒醒 05/29 15:03
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
3F:→ LaPass: 是在android上,不過這應該不會有影響才對 05/29 15:15
4F:→ LaPass: 用 thread.interrupt() 可以叫的醒,不過覺得用那種方式去 05/29 15:22
5F:→ LaPass: 叫執行序不太好... 05/29 15:22
6F:→ LaPass: 因為可能作到一半(非block狀態下)被打斷 05/29 15:26
7F:推 Frozenmouse: 你兩個Thread拿到的this是一樣的嗎? 05/29 17:25
8F:推 Frozenmouse: 如果兩條thread操作的DrawRunnable是同一個,這code 05/29 17:37
9F:→ Frozenmouse: 看起來沒問題…orz 05/29 17:37
10F:→ LaPass: 我確認一下..... 05/29 18:18
11F:→ LaPass: 對不起,是我耍蠢了 m(_ _)m 05/29 19:22