From the course: Complete Guide to Parallel and Concurrent Programming with Java

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Semaphore: Java demo

Semaphore: Java demo

- [Instructor] For this Java example, I'll use a counting Semaphore to control access and keep track of the number of available ports on a cell phone charger. This class named CellPhone has a static Semaphore variable named charger on line 9, which I've initialized to have a value of 4, representing the number of charger ports available to connect to. In the cell phone's run method, it will try to acquire the Semaphore on line 17. If the Semaphore is not available because its value is 0, then the thread will wait there until a charging port opens up and the Semaphore is released. Once a cell phone thread has acquired the Semaphore, it prints a message that it's charging and then sleeps for a random amount of time from one to two seconds. After that, the cell phone will execute the finally clause on line 22, which prints a message that it's done charging and then releases the Semaphore to increment its value so another thread can acquire it. Down in the main method, I just use a for…

Contents