// Simplified code to limit access to a single thread. // Unlike simple lock, you can use the wait/notify // mechanism to limit the number of customers, // not necessarily just to a single customer. /** * true if this code is too busy to take on more * customers. Volatile so all threads see the freshest * possible copy. */ private volatile boolean busy = false; ... // wait if there is a customer already using this code. synchronized ( this ) { // don't need to wait if this code is not busy. while ( busy ) { try { this.wait(); } catch ( InterruptedException e ) { // likely our turn now } } // stop other customer from coming in. busy = true; } ... // I'm done synchronized( this ) { // let next customer in. busy = false; // wake up one of the waiting customers, if any. this.notify(); }