作者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/cn.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