The use of Semaphore (semaphore) in Java

Source: Internet
Author: User
Tags semaphore

The role of Semaphore:

In Java, the use of the Synchronized keyword and the lock lock enable concurrent access control of the resource, allowing only threads to access the resource in the critical section at the same time (except for read locks), the main purpose of which is to solve the problem of inconsistent data caused by multiple threads concurrent with the same resource. In another scenario, a resource has multiple copies available for simultaneous use, such as multiple printers in the printer room and multiple pits in the toilet for simultaneous use, in which case Java provides additional concurrency access control-concurrent access control for multiple copies of the resource, The amount of semaphore that is learned today is one of them.

A preliminary study on semaphore realization Principle:

Semaphore is used to protect access to one or more shared resources, and the semaphore internally maintains a counter with a value of the number of shared resources that can be accessed. To access a shared resource, a thread obtains the semaphore first, and if the semaphore counter value is greater than 1, meaning that a shared resource can be accessed, subtract 1 from its counter value, and then access the shared resource.

If the counter value is 0, the thread enters hibernation. When a thread finishes using the shared resource, the semaphore is released and the counter inside the semaphore is incremented by 1, before the thread that enters hibernation is awakened and attempts to obtain the semaphore again.

Use of Semaphore:

Semaphore need to build a parameter to specify the number of shared resources, semaphore after the completion of the construction is to obtain semaphore, shared resources after the use of the release semaphore.

[Java]View PlainCopyprint?
    1. Semaphore Semaphore = new Semaphore (N,true);
    2. Semaphore.acquire ();
    3. Do something here
    4. Semaphore.release ();

The following code is simulated to control the concurrent use of the mall toilets:

Importjava.util.concurrent.*;ImportJava.util.concurrent.locks.ReentrantLock;ImportJava.util.*;Import Staticnet.mindview.util.print.*;classResourcemanage {Private FinalSemaphore Semaphore; Private Booleanresourcearray[]; Private FinalReentrantlock Lock;  PublicResourcemanage () { This. Resourcearray =New Boolean[10];//Storage Resource Status         This. Semaphore =NewSemaphore (10,true);//control the use of 10 shared resources, share using FIFO-first-out fair mode, signal volume in fair mode, first to get the semaphore first         This. Lock =NewReentrantlock (true);//Fair mode lock, first come first select         for(inti = 0; I < 10; i++) {Resourcearray[i]=true;//Initialize as a resource is available        }    }     Public voidUseresource (intUSERID)throwsinterruptedexception {semaphore.acquire (); Try {            //Semaphore.acquire ();            intid = Getresourceid ();//takes up a resourceSystem.out.print ("userid:" + userid + "Using resource, Resource ID:" + id + "\ n")); Thread.Sleep (100);//Do something, equivalent to using resourcesResourcearray[id] =true;//Exit this resource}Catch(interruptedexception e) {e.printstacktrace (); } finally{semaphore.release ();//release semaphore, counter plus 1        }    }    Private intGetresourceid () {intid =-1;        Lock.lock (); Try {            //Lock.lock ();//Although the use of lock control synchronization, but because only a simple array traversal, the efficiency is very high, so basically does not affect performance.              for(inti = 0; I < 10; i++) {                if(Resourcearray[i]) {Resourcearray[i]=false; ID=i;  Break; }            }        } Catch(Exception e) {e.printstacktrace (); } finally{lock.unlock (); }        returnID; }} Public classResourceuserImplementsRunnable {PrivateResourcemanage Resourcemanage; Private intuserId;  PublicResourceuser (Resourcemanage resourcemanage,intuserId) {         This. Resourcemanage =Resourcemanage;  This. UserId =userId; }     Public voidrun () {System.out.print ("UserID:" + userid + "prepare to use resources ... \ n"); Try{resourcemanage.useresource (userId); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } System.out.print ("UserID:" + userid + "Use resource complete ... \ n"); }     Public Static voidMain (string[] args) {resourcemanage resourcemanage=NewResourcemanage (); thread[] Threads=Newthread[100];  for(inti = 0; I < 100; i++) {thread thread=NewThread (NewResourceuser (Resourcemanage, i));//Create multiple resource usersThreads[i] =thread; }         for(inti = 0; I < 100; i++) {thread thread=Threads[i]; Try{Thread.Start ();//Start Thread}Catch(Exception e) {e.printstacktrace (); }        }    }
Userid:2 preparing to use resources ... userid:6 preparing to use resources ... userid:4 preparing to use resources ... userid:0 preparing to use resources ... userid:3 preparing to use resources ... userid:1 preparing to use resources ... Userid:8 preparing to use resources ... userid:9 preparing to use resources ... userid:10 preparing to use resources ... userid:1 using resources, resource ID:5Userid:3 is using resource, resource ID:4Userid:6 is using resource, resource ID:2userid:0 is using resource, resource ID:3Userid:7 preparing to use resources ... userid:2 using resources, resource ID:0Userid:4 is using resource, resource ID:1Userid:5 preparing to use resources ... userid:13 preparing to use resources ... userid:7 using resources, resource ID:9Userid:12 preparing to use resources ... userid:11 preparing to use resources ... userid:10 using resources, resource ID:8userid:15 preparing to use resources ... userid:9 using resources, resource ID:7Userid:8 is using resource, resource ID:6Userid:16 preparing to use resources ... userid:14 preparing to use resources ... userid:18 preparing to use resources ... userid:17 preparing to use resources ... userid:20 preparing to use resources ... userid:19 preparing to use resources ... userid:92 preparing to use resources ... userid:93 preparing to use resources ... userid:94 preparing to use resources ... userid:95 preparing to use resources ... userid:96 preparing to use resources ... userid:97 preparing to use resources ... userid:99 preparing to use resources ... userid:98 preparing to use resources ... userid:10 use resource complete ... userid:5 using resource, resource ID:0Userid:12 is using resource, resource ID:2userid:16 is using resource, resource ID:5userid:18 is using resource, resource ID:8userid:17 is using resource, resource ID:9userid:13 is using resource, resource ID:1Userid:3 Use resource Complete ... userid:0 use resource complete ... userid:1 use resource complete ... userid:2 use resource complete ... userid:4 use resource complete ... userid:9 use of resources ... Userid:7 Use resource Complete ... userid:6 use resource complete ...

Finally, in addition to controlling concurrent access control for multiple copies of a resource, semaphore can also use binary semaphores to implement concurrent access control functions like the Synchronized keyword and lock lock.

The use of Semaphore (semaphore) in Java

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.