0
ReceivingThread永远没有机会执行并且SendingThread KEEEEEEPPPSSS .......在执行时完全不可能完全锁定Semaphore对象,这是不是完全可能? 我从Jakob Jenkov concurrency tutorial是自定义信号量,它的使用甚至正确吗?
得到这个例子有人可以详细说明和解释下面的例子关于信号如何实际上像一个信号量?
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException{
while(!this.signal) wait();
this.signal = false;
}
}
public class SendingThread {
Semaphore semaphore = null;
public SendingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run(){
while(true){
//do something, then signal
this.semaphore.take();
}
}
}
public class RecevingThread {
Semaphore semaphore = null;
public ReceivingThread(Semaphore semaphore){
this.semaphore = semaphore;
}
public void run(){
while(true){
this.semaphore.release();
//receive signal, then do something...
}
}
}
class User{
public static void main(){
Semaphore semaphore = new Semaphore();
SendingThread sender = new SendingThread(semaphore);
ReceivingThread receiver = new ReceivingThread(semaphore);
receiver.start();
sender.start();
}
}
我相信,就像你一样,想要回答这个问题的人会“看到”适用的“延伸线索”,并会原谅我的真正监督。我看到你关于进一步阅读的观点。我希望如果有人能够指出我在教程中的例子中的重要差异,并“引导我”了解Semaphore如何“成长”。 – VedVrat 2014-10-09 14:09:43