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.
精彩评论