开发者

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) {
         tr开发者_运维技巧y {
            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. If a request comes from the jsp (Client) and goes through this class, will the Thread (the request from JSP ) wait and notify automatically?


I would highly recommend using the java.util.concurrent.Semaphore from the standard library instead of writing a custom Semaphore implementation. Only to mention one reason why this generally is a better idea: notify does not give any FIFO guarantees (from 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. and this tutorial from Thomas Darimont.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜