Java multithreading-new features-semaphore semaphore

Source: Internet
Author: User

Brief introduction
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.

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

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.

Package Cn.thread;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.semaphore;/** * Semaphore * * @author Lin Yi-chin * @version 1.0 2013-7-25 pm 02:03:40 */public class Semaphoretes t {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 () * 10000));                        After the visit, Release semp.release (); Availablepermits () refers to how many of the current beacon libraries can be used by the System. OUT.PRINTLN ("-----------------" + semp.availablepermits ());                    } catch (Interruptedexception e) {e.printstacktrace ();            }                }            };        Exec.execute (run);    }//Exit thread pool Exec.shutdown (); }}
Accessing:0accessing:1accessing:2accessing:4accessing:6accessing:8-----------------0----------------- 1accessing:3-----------------1accessing:5accessing:9-----------------0-----------------1accessing:7accessing: -----------------0-----------------1accessing:11-----------------1accessing:12-----------------1Accessing: 13accessing:14-----------------0-----------------1accessing:15-----------------0accessing:16----------------- 1accessing:17-----------------1accessing:18-----------------1accessing:19-----------------0Accessing: 20accessing:21-----------------0accessing:22-----------------0-----------------1accessing:23----------------- 1accessing:24-----------------0accessing:25accessing:26-----------------0-----------------1accessing:27------- ----------1accessing:28-----------------1accessing:29accessing:30-----------------0-----------------1Accessing :-----------------1accessing:32-----------------1accessing:33-----------------1accessing:34accessing:35-----------------0-----------------1accessing:36-----------------1accessing:37-----------------1accessing:38---- -------------1accessing:39-----------------1accessing:40accessing:41-----------------0----------------- 1accessing:42accessing:43-----------------0accessing:44-----------------0-----------------1accessing:45------- ----------1accessing:46-----------------1accessing:47-----------------1accessing:48-----------------1Accessing :-----------------1-----------------2-----------------3-----------------4-----------------5

Java Multithreading-new features-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: 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.