Java Semaphore Semaphore Introduction

Source: Internet
Author: User
Tags semaphore

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. The semaphore of the Java Concurrency Library makes it easy to control the semaphore, Semaphore can control the number of simultaneous accesses to a resource, obtain a license through acquire (), and release () releases a license if there is no 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.

Semaphore maintains the number of current accesses, provides a synchronization mechanism, and controls the number of simultaneous accesses. In the data structure, the linked list can save the "infinite" node, and the semaphore can be used to realize the finite-size linked list. In addition, the re-entry lock Reentrantlock can also implement this function, but the implementation is more complicated.

The demo below states that there is only 5 licensed semaphore, and 20 threads have access to this resource, obtaining and releasing access licenses through Acquire () and release ().

 Packagecom.test;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.Semaphore; Public classTestsemaphore { 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 < 20; 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 (); System.out.println ("-----------------"+semp.availablepermits ()); } Catch(interruptedexception e) {e.printstacktrace ();                                      }                                                  }                      };             Exec.execute (run); }             //exit thread poolExec.shutdown (); }} 

The results of the implementation are as follows:

accessing:0

Accessing:1

Accessing:3

Accessing:4

Accessing:2

-----------------0

Accessing:6

-----------------1

Accessing:7

-----------------1

Accessing:8

-----------------1

Accessing:10

-----------------1

Accessing:9

-----------------1

Accessing:5

-----------------1

Accessing:12

-----------------1

Accessing:11

-----------------1

Accessing:13

-----------------1

Accessing:14

-----------------1

Accessing:15

-----------------1

Accessing:16

-----------------1

Accessing:17

-----------------1

Accessing:18

-----------------1

Accessing:19

Java Semaphore Semaphore Introduction

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.