Java core knowledge point learning-Semaphore learning in the thread, public toilet queuing strategy

Source: Internet
Author: User

1. What is Semaphore? A counting semaphore. conceptually, a semaphore maintains a set of permits. each acquire blocks if necessary until a permit is available, and then takes it. each release adds a permit, potentially releasing a blocking acquirer. however, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly. semaphores are often used to restrict the number o F threads than can access some (physical or logical) resource. the above is an official introduction to this class. semaphores (Semaphore), sometimes called signal lights, are a facility used in a multi-threaded environment and are responsible for coordinating various threads, to ensure that they can use public resources correctly and reasonably. For example, there are only three seats in the public restroom, and 10 people need to go to the toilet. the first three places are empty, so there will be three people occupying the trap, others only need to wait outside. if one of the seven persons is waiting to go to the toilet. there may also be two OK persons at the same time, so there will also be two makeup personnel at the same time. simply put, you must have a space to go to the bathroom. although the example of going to the toilet is unsightly, it is impressive. I would like to give an example of taking money from an ATM. the role of Semaphore is to control the allocation of locations. Generally, the allocation of locations is random. You can set rules for sorting objects during Object Instantiation. let's look at the code: copy the code package com. amos. concurrent; import java. util. random; import java. util. concurrent. executorService; import java. util. concurrent. executors; import java. Util. concurrent. semaphore;/*** @ ClassName: SemaPhoreTest * @ Description: "signal light" * @ author: amosli * @ email: hi_amos@outlook.com * @ date Apr 25,201 4 12:06:22 AM */public class SemaPhoreTest {public static void main (String [] args) {ExecutorService threadPool = Executors. newCachedThreadPool (); final Semaphore semaphore = new Semaphore (3); for (int I = 0; I <10; I ++) {threadPool.exe cute (new Runnable () {Public void run () {try {semaphore. acquire (); // obtain an available permits} catch (Exception e) {e. printStackTrace ();} System. out. println ("Thread" + Thread. currentThread (). getName () + "entered. "+" currently there are "+ (3-semaphore.availablePermits () +" Threads entering "); try {Thread. sleep (new Random (). nextInt (1000);} catch (InterruptedException e) {e. printStackTrace ();} System. out. println ("Thread" + Thread. currentThread (). getName () + "Leaving... "); semaphore. release (); // release a thread System. out. println ("Thread" + Thread. currentThread (). getName () + "left. currently, there are "+ (3-semaphore.availablePermits () +" concurrent ") ;}}}} how can I ensure that the copied code is orderly? The above Code does not guarantee the order. If there is a FIFO order, that is, the first-in-first-out principle, there is a queue, and the toilet will be queued, you only need to change the above code line. final Semaphore semaphore = new Semaphore (3, true); this way, the other code remains unchanged. as shown in figure 3. code Description 1 ). how to Create Semaphore? New Semaphore (3); // unordered by default, the creation is unordered. new Semaphore (3, true); // ordered 2) how to get a "slot "? First, the program checks whether the "pit" is full. If it is not full, it can be allocated as needed. The specific code is as follows: try {semaphore. acquire (); // obtain an available permits} catch (Exception e) {e. printStackTrace ();} Then, after the allocation, the location of the pitfall will be unavailable. 3) how to release a "slot "? Semaphore. release (); // after a thread is released, the pitfall is available. 4. extension-copy the code For example in the official example. here is a class that uses a semaphore to control access to a pool of items: class Pool {private static final int MAX_AVAILABLE = 100; private final Semaphore available = new Semaphore (MAX_AVAILABLE, true); public Object getItem () throws InterruptedException {available. acquire (); return getNextAvailableItem ();} public void PutItem (Object x) {if (markAsUnused (x) available. release ();} // Not a participant ly efficient data structure; just for demo protected Object [] items =... whatever kinds of items being managed protected boolean [] used = new boolean [MAX_AVAILABLE]; protected synchronized Object getNextAvailableItem () {for (int I = 0; I <max_available; ++ I) {if (! Used [I]) {used [I] = true; return items [I] ;}} return null; // not reached} protected synchronized boolean markasunused (object item) {for (int I = 0; I <max_available; ++ I) {if (item = items [I]) {if (used [I]) {used [I] = false; return true;} else return false ;}}

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.