Java realizes flow control-semaphore__java

Source: Internet
Author: User

Online similar to a lot of articles, not to say, directly on the code:

[java]  View plain  copy/**   *  flow control (semaphore implementation)    *    * @ author ln   *   */   public class flowcontrol {          /**       *  Maximum traffic         */       private static final int max_ access_count = 20;          /**        *  can only have max_access_count number of threads simultaneous access        */        private static final semaphore semaphore = new semaphore (MAX_ACCESS_ COUNT);          public static void main (String[]  args)  {           //  thread pool        &nbsP;    executorservice exec = executors.newcachedthreadpool ();              //  Simulation 30 clients             for  (int i = 0; i < 30; i++)  {                runnable run =  new runnable ()  {                     @Override                     public void run ()  {                        try  {                       &nbThe access is discarded if no permission is available within the sp;    // 1 seconds.                             if  (Semaphore.tryacquire (1, timeunit.seconds))   {                    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Executing ...");                                 //do some things ...                                 thread.sleep (2 * 1000);                    &nbsP;           system.out.println ("execution completed.") ");                            } else {                           &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN ("Access denied ...") ");                            }                        } catch  ( Interruptedexception e)  {  

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.