Java Semaphore semaphore

Source: Internet
Author: User

Semaphore

The semaphore is divided into single-valued and multi-valued two, which can only be obtained by one thread, the latter of which may be obtained by several threads.

Semaphore implementation of the function is similar to the toilet has 5 pits, if there are 10 people to the toilet, then at the same time only how many people to go to the toilet? At the same time only 5 people can occupy, when any one of the 5 people out of the way, one of the other 5 waiting for a person to occupy. The other 5 people who are waiting can be given a chance at random, or they can be given an opportunity in the order of first served, depending on the parameter options passed in when constructing the semaphore object. The semaphore object of a single semaphore can implement a mutex function, and it can be a thread that obtains a "lock", and another thread releases the "lock", which can be applied to some occasions of deadlock recovery.

Let's take a car park operation for 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, and each car is like a thread, and the gatekeeper acts as the semaphore.

Further, the characteristics of the semaphore are as follows: The semaphore is a non-negative integer (number of spaces), and all threads (vehicles) passing through it will subtract that integer by one (using resources), and when the integer value is zero, All threads that are trying to pass through it will be in a wait state. On the semaphore we define two actions: Wait (wait) and release (release). When a thread calls the wait 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.

Semaphore (int  permits, Boolean fair)// creates Semaphore with a given number of licenses and a given fairness setting. 

You can also set whether the semaphore is in fair mode, and if executed in a fair manner, the thread will be executed in the order of arrival (FIFO), and if it is unfair, then the request may be queued to the head of the queue.

Use

Semaphore can control the number of simultaneous accesses to a resource, obtain a license through acquire (), and release () releases a license if no wait is available.

ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.Semaphore; Public classSemaphoretest { Public Static voidMain (string[] args) {//thread PoolExecutorservice exec =Executors.newcachedthreadpool (); //can only be accessed by 5 threads at a time        FinalSemaphore semp =NewSemaphore (5); //simulate 20 Client access         for(intindex = 0; Index < 50; index++) {            Final intNO =index; Runnable Run=NewRunnable () { Public voidrun () {Try {                        //obtaining a licenseSemp.acquire (); System.out.println ("Accessing:" +NO); Thread.Sleep ((Long) (Math.random () * 10000)); //after the visit, releasesemp.release (); //availablepermits () refers to how many of the current beacon libraries can be usedSystem.out.println ("-----------------" +semp.availablepermits ()); } Catch(interruptedexception e) {e.printstacktrace ();            }                }            };        Exec.execute (run); }        //exit thread poolExec.shutdown (); }}
accessing:0Accessing:1Accessing:2Accessing:4Accessing:6Accessing:8-----------------0-----------------1Accessing:3-----------------1Accessing:5Accessing:9-----------------0-----------------1Accessing:7Accessing:-----------------0-----------------1Accessing:-----------------1Accessing:-----------------1Accessing:13Accessing:-----------------0-----------------1Accessing:-----------------0Accessing:1-----------------Accessing:-----------------1Accessing:-----------------1Accessing:-----------------0Accessing:20Accessing:-----------------0Accessing:-----------------0-----------------1Accessing:-----------------1Accessing:-----------------0Accessing:25Accessing:-----------------0-----------------1Accessing:-----------------1Accessing:-----------------1Accessing:29Accessing:-----------------0-----------------1Accessing:-----------------1Accessing:1-----------------Accessing:-----------------1Accessing:34Accessing:-----------------0-----------------1Accessing:1-----------------Accessing:PNS-----------------1Accessing:-----------------1Accessing:1-----------------Accessing:40Accessing:-----------------0-----------------1Accessing:42Accessing:0-----------------Accessing:-----------------0-----------------1Accessing:-----------------1Accessing:1-----------------Accessing:-----------------1Accessing:-----------------1Accessing:-----------------1-----------------2-----------------3-----------------4-----------------5
I'm the dividing line of the king of the Land Tiger.

Reference: http://www.cnblogs.com/linjiqin/archive/2013/07/25/3214676.html

Java Semaphore semaphore

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.