2014-10-09 76 views
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(); 
    } 
} 

回答

0

首先,“sender”和“receiver”似乎都不是线程。 (他们不延长“线程”。)

有问题的信号确实表现得像有可能等待它被释放含义的信号,它不是并发信号安全。

另一方面,你已经从教程中取出代码。 阅读教程,并假设它试图教你一些东西。 它看起来像下一段落解决您的问题。

+0

我相信,就像你一样,想要回答这个问题的人会“看到”适用的“延伸线索”,并会原谅我的真正监督。我看到你关于进一步阅读的观点。我希望如果有人能够指出我在教程中的例子中的重要差异,并“引导我”了解Semaphore如何“成长”。 – VedVrat 2014-10-09 14:09:43