The Semaphore (semaphore) acts as the "semaphore" under the operating system concept. It provides the same functionality as the amount of available resource semaphores in a critical section.
Take a car park operation as an example. For the sake of simplicity, suppose the parking lot has only three parking spaces, and the first three spaces are empty. At the same time, if five vehicles were to come, the janitor would allow three of them to enter the barrier, then put down the car, the rest of the car must wait at the entrance, and then the car will have to wait at the entrance. At this time, there is a car left the parking lot, the janitor learned, open the car block, put in a car, if you leave two again, then can put two, so reciprocating.
In this parking system, parking spaces are public resources (critical area resources), and each car is like a thread, and the gatekeeper acts as a semaphore.
Further, the characteristics of the semaphore are as follows: The semaphore is a nonnegative integer (number of spaces), and all threads (vehicles) passing through it will subtract one (through it, of course, to use the resource), and when that integer value is zero, all threads attempting to pass through it will be in the waiting state. On the semaphore we define two operations: acquire (get resources) and release (freeing resources). When a thread invokes the acquire (get Resource) operation, it either passes the semaphore down by one, or waits until the semaphore is greater than one or times out. Release is actually an add operation on the semaphore, which corresponds to the vehicle leaving the parking lot, which is called "release" because the plus operation actually frees up the resources that are guarded by semaphores.
Packagecom.lt.thread.SamephoreTest;ImportJava.util.concurrent.Semaphore;/*** Created by Ltao on 2015-2-9.*/ Public classParkingImplementsRunnable {Private intcount; PrivateSemaphore Semaphore; Public intGetCount () {returncount; } Public voidSetCount (intcount) { This. Count =count; } PublicSemaphore Getsemaphore () {returnSemaphore; } Public voidSetsemaphore (Semaphore Semaphore) { This. Semaphore =Semaphore; } PublicParking (intcount) { This. count=count; This. semaphore=NewSemaphore (count); } Public voidparking () {Try{semaphore.acquire (); Try{Thread.Sleep (100); System.out.println (Thread.CurrentThread (). GetName ()+ "Find a paking space"); } Catch(interruptedexception e) {e.printstacktrace (); } } Catch(interruptedexception e) {e.printstacktrace (); } finally{System.out.println (Thread.CurrentThread (). GetName ()+ "Release a paking space"); Semaphore.release (); }} @Override Public voidrun () { This. Parking (); } Public Static voidMain (string[] args) {Parking Parking=NewParking (5); thread[] Threads=NewThread[13]; for(inti=0;i<threads.length;i++) {Threads[i]=NewThread (parking, "thread" +i); } for(inti=0;i<threads.length;i++) {Threads[i].start (); } }}
The semaphore semaphore in Java