简体   繁体   English

需要帮助理解线程等待和通知

[英]Need help in understanding Thread wait and notify

class Semaphore {
   private int count=100;
   public Semaphore(int n) {
      this.count = n;
   }

   public synchronized void acquire() {
      while(count == 0) {
         try {
            wait();
         } catch (InterruptedException e) {
            //keep trying
         }
      }
      count--;
   }

   public synchronized void release() {
      count++;
      notify(); //alert a thread that's blocking on this semaphore
   }
}

Currently I am supporting 100 users. 目前我支持100个用户。 If a request comes from the jsp (Client) and goes through this class, will the Thread (the request from JSP ) wait and notify automatically? 如果请求来自jsp(客户端)并通过此类,那么Thread(来自JSP的请求)是否会自动waitnotify

I would highly recommend using the java.util.concurrent.Semaphore from the standard library instead of writing a custom Semaphore implementation. 我强烈建议使用标准库中的java.util.concurrent.Semaphore ,而不是编写自定义Semaphore实现。 Only to mention one reason why this generally is a better idea: notify does not give any FIFO guarantees (from Object.notify() ): 仅举几个原因,这通常是一个更好的主意: notify不提供任何FIFO保证(来自Object.notify() ):

The choice is arbitrary and occurs at the discretion of the implementation 选择是任意的,由实施决定

You do not have to write a semaphore yourself. 您不必自己编写信号量。

Take a look at the Java 6 documentation for Semaphore . 查看Semaphore的Java 6文档。 and this tutorial from Thomas Darimont. 和Thomas Darimont的这个教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM