From the course: Parallel and Concurrent Programming with Java 2

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Semaphore: Java demo

Semaphore: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 2

Start my 1-month free trial

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 nine, which I've initialized to have a value of four, 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 zero, 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…

Contents