自定义信号量及其用法是否正确?



难道ReceivingThread永远没有机会执行而SendingThread KEEEEEEPPSSS不是完全可能的吗。。。。。。。在执行时根本不保留对Semaphore对象的锁定?我从Jakob Jenkov并发教程中得到了这个例子

有人能详细说明并解释下面的例子吗?关于信号量实际上是如何表现得像信号量的?

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();  
    }  
}

首先,"sender"one_answers"receiver"似乎都不是线程。(它们不会扩展"线程"。)

有问题的信号量的行为确实像信号量,这意味着可以等待它被释放,但对于并发信号来说是不安全的。

另一方面,您已经断章取义地从教程中获取了代码。阅读教程,并假设它试图教你一些东西。接下来的段落似乎解决了您的担忧。

相关内容

最新更新