Introduction and use of Java semaphore

Source: Internet
Author: User
Tags semaphore

A count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. The thread that gets the semaphore can enter the code or wait. Obtain and release access licenses through Acquire () and release ().

Example: If you are designing a database reader, the person using the program is more tentative 20, but also only allow 5 clients to use the program to the database operation, only before the release can be used later programs

The pseudo code is as follows:

Import java.util.concurrent.*;/** * by LV Xiao long **/ Public classApp { Public Static voidMain (string[] args) {//thread PoolExecutorservice exec =Executors.newcachedthreadpool (); //impersonation can only be accessed by 5 clients at a timeFinal Semaphore semp =NewSemaphore (5); //simulate 20 Client access         for(intindex =0; Index < -; index++) {FinalintNO =index; Runnable Run=NewRunnable () { Public voidrun () {Try {                        //obtaining a licenseSemp.acquire (); System. out. println ("Accessing:"+NO); Thread.Sleep ((Long) (Math.random () *10000)); //after the access, release, if the following statement is masked, the console can only print 5 records, and then the thread has been blockedsemp.release (); } Catch(Interruptedexception e) {}};        Exec.execute (run); }        //exit thread poolExec.shutdown (); }}

Introduction and use of Java semaphore

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.