Java Multithreading-semaphore (Semaphore)

Source: Internet
Author: User


The semaphore (Semaphore), sometimes called a semaphore, is a facility used in a multithreaded environment that coordinates individual threads to ensure that they are able to use public resources correctly and rationally.

a count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. The thread that gets the semaphore can enter the code or wait. Obtain and release access licenses through Acquire () and release ().

ConceptThe 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.

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, 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 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 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.

In Java, 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.
The JDK is defined as follows:
Semaphore (int permits, Boolean fair)
creates a semaphore with the given number of licenses and a given fairness setting.

Semaphore is currently used in multi-threaded environments, the operating system semaphore is a very important concept, in the process of control has been applied. Java Concurrency Library semaphore can easily complete semaphore control, Semaphore can control the number of simultaneous accesses to a resource, obtain a license through acquire (), and release () releases a license if it is not waiting. For example, under Windows, you can set the maximum number of client accesses for a shared file.

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.

code example
Import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.semaphore;/** * datetime:2015 January 1 pm 6:41:01 * */public class Semaphore {public static void main (string[] args)        {//thread pool Executorservice exec = Executors.newcachedthreadpool ();        Only 5 threads can access the final Semaphore semp = new Semaphore (5) at a time;            Simulates 20 client access for (int index = 0; index < index++) {final int NO = index;                         Runnable run = new Runnable () {public void run () {try {//Get license                        Semp.acquire ();                        System.out.println ("Accessing:" + NO);                        Thread.Sleep ((Long) (Math.random () * 6000));                        After the visit, Release semp.release (); Availablepermits () refers to how many of the current beacon libraries can be used System.out.println ("-----------------" + semp.availablePermits ());                    } catch (Interruptedexception e) {e.printstacktrace ();            }                }            };        Exec.execute (run);    }//Exit thread pool Exec.shutdown (); }}

Java Multithreading-semaphore (Semaphore)

Related Article

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: 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.