The semaphore of Java concurrent programming

Source: Internet
Author: User

Signal Volume (Semaphore). It is sometimes called a semaphore. is a facility used in a multithreaded environment that coordinates threads to ensure that they can use public resources correctly and rationally.


A count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary. Each acquire () is blocked before the license is available, and then the license is acquired. Each release () adds a license. This may release a blockage of the acquiring person.

But. Without the use of the actual license object, Semaphore only counts the number of available licenses and takes corresponding actions. The thread that gets the semaphore can enter the code. Otherwise, wait. Obtain and release access licenses through Acquire () and release ().

Package Com.lala.shop;import Java.time.duration;import Java.time.instant;import java.util.arrays;import Java.util.collections;import Java.util.list;import Java.util.concurrent.countdownlatch;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Java.util.concurrent.Semaphore ; Import Java.util.concurrent.timeunit;public class Semaphoredemo {/** * This shows a sample: 10 people going to the bathroom together * Assuming that only one person can go to the bathroom at a time: 1+2 +3+4+5+6+7+8+9+10=55 min * Suppose you can go to the toilet with 10 people at a time. Total time required: 10 minutes */static void demonstration (int num) throws exception{string[] users = {"Liu Mei", "Nod", "Summer Snow", "Liu Xing", "Xia Xia", "Grandpa", "Granny "," Mary "," Hu Unified "," an Lam Ninh "}; Countdownlatch CDL = new Countdownlatch (users.length); integer[] times = {1,2,3,4,5,6,7,8,9,10}; List<integer> timelist = Arrays.aslist (times); Collections.shuffle (Timelist); Semaphore SPH = new Semaphore (num); Executorservice runner = Executors.newcachedthreadpool (); Instant start = Instant.now (); for (int i=0; i<users.length; i++) {Final int index = I;runner.submit (), {try {///get Beacon, quasiToilet Sph.acquire (); Long time = Timelist.get (index); TimeUnit.SECONDS.sleep (time); System.out.println (Users[index] + "toilet complete. Total time Spent: Cdl.countdown ();//The thing has been done, release the Signal Sph.release ();} catch (Exception e) {e.printstacktrace ();}});} Runner.shutdown (); cdl.await () Instant end = Instant.now ();D uration speed = Duration.between (start, end); Long seconds = Speed.getseconds ();///sec means System.out.println ("all the toilets (only one can have" + num + "People going to the toilet at a time), which takes a total of hours:" + seconds);} public static void Main (string[] args) throws exception{demonstration (5);}}

Assume that you call the following method:

Demonstration (5);

Then, the output is:

Summer snow to get the toilet done. Total Elapsed Time: 1
Summer Rain toilet completed, spent time: 3
Liu Xing toilet completed, spent time: 4
Grandpa Toilet completed, spent time: 6
Nod toilet completed, spent time: 8
Liu Mei toilet completed, spent time: 9
Hu Unified to do the toilet. Total Elapsed Time: 2
Marie toilet completed, spent time: 7
An Lam Ninh toilet completed, spent time: 5
Granny toilet complete, spend time: 10
All the toilets (only 5 people can get to the toilet at a time), it takes a total of 13


Assume that you call the following method:

Demonstration (1);

Then, the output is:

Liu Mei toilet completed, spent time: 10
Nod toilet completed, spent time: 6
Summer snow toilet completed, spent time: 3
Liu Xing to get the toilet done. Total Elapsed Time: 9
Summer rains are done by toilet. Total Elapsed Time: 8
Grandpa is done on the toilet. Total Elapsed Time: 4
Granny toilet complete, spend time: 1
Marie toilet complete. Total Elapsed Time: 5
Hu Unified toilet completed, spent time: 7
An Lam Ninh toilet completed, spent time: 2
All the toilets (only 1 people can get to the toilet at a time), it takes a total of 55


Assume that the call method is

Demonstration (10); The output is:

Summer Rain toilet completed, spent time: 1
Nod toilet completed, spent time: 2
Grandpa Toilet completed, spent time: 3
Liu Xing to get the toilet done. Total Elapsed Time: 4
Liu Mei toilet completed, spent time: 5
Hu Unified to do the toilet. Total Elapsed Time: 6
An Lam Ninh toilet completed, spent time: 7
Granny toilet complete, spend time: 8
Marie toilet completed, spent time: 9
Summer snow toilet completed, spent time: 10
All toilets (only 10 people can be potty at a time). Total time: 10

The semaphore of Java concurrent programming

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.