Semaphore (Java multithreaded concurrency) controlling the number of concurrent threads

Source: Internet
Author: User
Tags semaphore

1. Introduction
Semaphores (semaphore), sometimes referred to as semaphores, are a facility used in multi-threaded environments that coordinate threads to ensure that they can use public resources correctly and rationally.

2. The concept
Semaphore is divided into single and multivalued two, the former can only be obtained by one thread, the latter can be obtained by a number of threads.

Take a car park operation for example. For simplicity's sake, let's say that there are only three parking spaces in the parking lot, and that three parking spaces are empty. When five cars are in the same time, the doorman allows three of them to enter without hindrance, then puts down the car and the rest of the car has to wait at the entrance, after which the car has to wait at the entrance. At this time, there is a car out of the car park, the doorman learned, open the car block, into a car, if you leave two, you can put two vehicles, so reciprocating.

in this parking system, parking is a public resource, each car is like a thread, the gatekeeper is the role of the signal.

Further, the characteristic of the semaphore is as follows: The semaphore is a nonnegative integer (number of parking spaces), and all the threads (vehicles) that pass through it subtract the integer (through it, of course, to use resources), and when the integer value is zero, all the threads attempting to pass it are in the waiting state. We define two kinds of operations on the semaphore: Wait (Waiting) and release (releasing). When a thread invokes a wait operation, it either passes the semaphore by one or waits until the semaphore is greater than one or times out. Release is actually a plus operation on the semaphore, which corresponds to the vehicle leaving the car park, which is called "release" because the addition is actually releasing the resource that is guarded by the semaphore.

In Java, you can also set whether the semaphore is in fair mode, and if executed in a fair manner, the thread will execute in the order in which it arrives (FIFO), and if it is unfair, then it may be possible to queue the head after the request.
The JDK is defined as follows:
Semaphore (int permits, Boolean fair)
Creates a semaphore with the given number of licenses and a given fair setting.

Semaphore is currently being used in a multi-threaded environment, the signal volume of the operating system is an important concept, and it is applied in Process control. Java Concurrent Library semaphore can easily complete semaphore control, Semaphore can control the number of simultaneous access to a resource, through acquire () get a license, if not wait, and release () released a license. For example, you can set the maximum number of client accesses to a shared file under Windows.

Semaphore realize the function is similar to the toilet has 5 pits, if there are 10 people to go to the toilet, then can only have how many people to the toilet. At the same time only 5 people can occupy, when one of the 5 people out of the way, the other 5 waiting for another person can occupy. The other 5 people waiting for them can be randomly given priority, or get an opportunity in arrival order, depending on the parameter options that are passed in when the semaphore object is constructed. The semaphore object of a single semaphore can implement a mutex function, and it can be "locked" by one thread and released by another thread, which can be applied to some situations of deadlock recovery.

3. Case one:

Package semaphore;
Import Java.util.Random;
Import java.util.concurrent.*; public class Test {public static void main (string[] args) {//thread pool Executorservice executor = Executors.newcachedt
		Hreadpool ();
        Define semaphore, only 5 threads simultaneously access final semaphore semaphore = new semaphore (5);
			 Simulate 20 threads simultaneously access for (int i = 0; i < i++) {final int NO = i;
						Runnable Runnable = new Runnable () {public void run () {try {//Get license Semaphore.acquire (); Availablepermits () refers to how many of the current semaphore libraries can be used System.out.println ("thread" + thread.currentthread (). GetName () + "Enter, currently existing" + (5-s
					    Emaphore.availablepermits ()) + "concurrency");
						System.out.println ("index:" +no);
					    
						Thread.Sleep (New Random (). Nextint (1000) *10);	
					    SYSTEM.OUT.PRINTLN ("Thread" + thread.currentthread (). GetName () + "about to leave");

					
					After the visit, Release semaphore.release ();
					catch (Exception e) {e.printstacktrace ();
			
			}
				}
			}; Executor.execute (RunnABLE);
	//Exit thread pool Executor.shutdown ();
 }

}


4. Case two:

The following is a simulation of a connection pool that can be accessed at most 50 threads at the same time.

[Java]  View plain copy import java.util.uuid;   import java.util.concurrent.semaphore;    import java.util.concurrent.timeunit;      Public class testsemaphore  extends Thread {       public static void main ( String[] args)  {           int i = 0 ;           while  (i < 500)  {                i++;                new testsemaphore (). Start ();               try {                    thread.sleep (1);    &NBSP;&NBSP;&NBSp;         } catch  (interruptedexception e)  {                     E.printstacktrace ();               }            }       }          /**       *  Control of the number of concurrent access to a resource class   Control at the same time only 50 access        */       static  Semaphore semaphore = new semaphore (    static );   int timeout = 500;          public void run ()  {           try {           &Nbsp;    object connec = getconnection ();                system.out.println ("Get a Connection"  + connec);                thread.sleep (;  )             releaseconnection (Connec);           } catch  (interruptedexception e)  {                e.printstacktrace ();           }       }          public void releaseconnection (Object connec)  {            /*  Release Permission  */             Semaphore.release ();           system.out.println ("Free A Connection"  + connec);       }           Public object getconnection ()  {           try  

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.