14.java5 's Semaphere Sync Tool

Source: Internet
Author: User
Tags semaphore

1 ImportJava.util.concurrent.ExecutorService;2 Importjava.util.concurrent.Executors;3 ImportJava.util.concurrent.Semaphore;4 5 /**6 * 14.JAVA5 's semaphere sync tool7 * Semaphore can maintain the number of threads currently accessing itself and provides a synchronization mechanism. 8 * Use semaphore to control the number of threads concurrently accessing resources, for example, to implement a9 * The number of concurrent accesses allowed by the file. Ten * The semaphore object of a single semaphore can implement the mutex function, and it can be One * One thread obtains a "lock" and another thread releases "lock", which can be applied to some occasions of deadlock recovery.  A  * @authorlitaiqing -  * -  */ the  Public classSemaphoretest { -      Public Static voidMain (string[] args) { -Executorservice Service =Executors.newcachedthreadpool (); -         FinalSemaphore SP =NewSemaphore (3); +          for(inti = 0; I < 10; i++) { -Runnable Runnable =NewRunnable () { +                  Public voidrun () { A                     Try { at Sp.acquire (); -}Catch(interruptedexception E1) { - e1.printstacktrace (); -                     } -SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () -+ "Enter, current already" + (3-sp.availablepermits ()) + "concurrency"); in                     Try { -Thread.Sleep ((Long) (Math.random () * 10000)); to}Catch(interruptedexception e) { + e.printstacktrace (); -                     } theSYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () *+ "Leaving soon"); $ sp.release ();Panax Notoginseng                     //The following code is sometimes executed inaccurately because it does not synthesize atomic units with the above code -SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () the+ "has left, currently has" + (3-sp.availablepermits ()) + "concurrency"); +                 } A             }; the Service.execute (runnable); +         } -     } $}

14.java5 's Semaphere Sync Tool

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.