Java notes--the understanding and application of semaphore semaphore

Source: Internet
Author: User

Use of the Java Semaphore semaphore:

In Java, the support for Semaphore Semaphore is provided.


The semaphore class is a count semaphore that must be freed by the thread that gets it,
This is typically used to limit the number of threads that can access some resources (physical or logical).


One semaphore has and only 3 operations, and they are all atomic: Initialize, increase, and decrease
Increase can be unblocked for a process;
The reduction allows a process to enter the block.

--If you want to reprint this article please indicate the reprint address "http://www.cnblogs.com/XHJT/p/3910406.html" Thank you--

Semaphores maintain a license set and, if necessary, block each thread before obtaining a license:
A given number of licenses are obtained from this semaphore, and threads are blocked until these licenses are available.
acquireuninterruptibly (int permits) {}
Each release () adds a license that may release a blocked fetch.
Semaphore only counts the number of available licenses and takes action accordingly.

How do I get Semaphore objects?
Public Semaphore (int Permits,boolean Fair)
Permits: Initialize the number of licenses available.
Fair: True if the semaphore is guaranteed to be granted in FIFO order at the time of requisition, otherwise false;

How do I get a license from the semaphore?
public void Acquire () throws Interruptedexception

How do I release a license and return the semaphore?
public void Release ()

code example:
20 people went to the bank to deposit, but the bank only two office counters, there are seats to go up to save money, there is no vacancy can only go to wait in line

 PackageCom.xhj.thread;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.Semaphore;/*** Application of thread semaphore semaphore * *@authorXiehejun **/ Public classSemaphorethread {Private intA = 0; /*** Bank Savings Class*/    classBank {Private intaccount = 100;  Public intGetaccount () {returnAccount ; }         Public voidSaveintMoney ) { Account+=Money ; }    }    /*** Thread Execution class, save 10 dollars each time*/    classNewthreadImplementsRunnable {PrivateBank Bank; PrivateSemaphore Semaphore;  PublicNewthread (Bank Bank, Semaphore Semaphore) { This. Bank =Bank;  This. Semaphore =Semaphore; } @Override Public voidrun () {intb = a++; if(Semaphore.availablepermits () > 0) {System.out.println ("Thread" + B + "Start, go to the bank, have a place to save immediately"); } Else{System.out.println ("Thread" + B + "Start, enter the bank, no location, go in line Wait Wait"); }            Try{semaphore.acquire (); Bank.save (10); System.out.println (b+ "account balance:" +Bank.getaccount ()); Thread.Sleep (1000); System.out.println ("Thread" + B + "Save your money and leave the bank");            Semaphore.release (); } Catch(interruptedexception e) {e.printstacktrace (); }        }    }    /*** Build threads, call internal classes, start saving*/     Public voidUsethread () {Bank Bank=NewBank (); //define 10 new numbersSemaphore Semaphore =NewSemaphore (2); //Create a cache thread poolExecutorservice es =Executors.newcachedthreadpool (); //Build 20 Threads         for(inti = 0; I < 10; i++) {            //executes a threadEs.submit (NewThread (NewNewthread (Bank, Semaphore)); }        //Close the thread poolEs.shutdown (); //get two licenses from semaphores and block threads until you get a licenseSemaphore.acquireuninterruptibly (2); System.out.println ("The staff were very friendly and the food was very nice."); //release two licenses and return them to the semaphoreSemaphore.release (2); }     Public Static voidMain (string[] args) {semaphorethread test=NewSemaphorethread ();    Test.usethread (); }}


face question thinking:
    In many cases, there may be multiple threads that require access to a small number of resources. It is assumed that several threads are running on the server that answer client requests. These threads need to connect to the same database, but at any one time
    can only get a certain number of database connections. How will you be able to effectively allocate these fixed number of database connections to a large number of threads?
   
Answer: 1. Plus synchronous lock to ensure that only one person can call this method at the same time, all other threads are queued, but in this case, even if you have 10 database links, there is always only one in the

         status. This will greatly waste the system resources, and the operating efficiency of the system is very low.


    2. Another approach, of course, is to use semaphores , which can greatly improve efficiency and performance by using the same number of semaphore licenses as the number of available connections in the database.

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.