Java semaphores Semaphore usage

Source: Internet
Author: User
Tags semaphore


When Semaphore semaphores are used, it is useful for fair scheduling. When multiple threads can be controlled to compete for resources, the maximum number of threads can be executed. The code is tested by hand as follows:

Note:

1. acquire () to obtain a license. If not, wait.
2. release a license for release ()
3. Semaphore can control the number of resources that can be accessed at the same time. The number of self-initialized resources is 1, which is executed in sequence.


Package com. i5a6. semp. test;
 
Import java. util. Random;
Import java. util. concurrent. ExecutorService;
Import java. util. concurrent. Executors;
Import java. util. concurrent. Semaphore;
 
Public class SemaphoreTest {
 
Private Semaphore semp;
 
Private ExecutorService executorPool;
 
Public SemaphoreTest (int threadNum ){
Semp = new Semaphore (threadNum );
ExecutorPool = Executors. newFixedThreadPool (threadNum );
 }
 
Public void doEnd (){
This.exe cutorPool. shutdown ();
 }
 
Public void doMsg (int num ){
Try {
Semp. acquire ();
ExecutorPool.exe cute (new HelloUExecutor (num ));
} Catch (InterruptedException e ){
E. printStackTrace ();
  }
 }
 
Class HelloUExecutor implements Runnable {
Private int num;
 
Public HelloUExecutor (int num ){
This. num = num;
  }
 
Random r = new Random ();
 
@ Override
Public void run (){
Try {
System. out. println (num );
Thread. sleep (r. nextInt (1000 ));
} Catch (Exception e ){
E. printStackTrace ();
} Finally {
Semp. release ();
   }
  }
 }
 
Public static void main (String [] args ){
// The initialization is 1-order execution.
SemaphoreTest st = new SemaphoreTest (5 );
For (int I = 0; I <20; I ++ ){
St. doMsg (I );
  }
St. doEnd ();
 }
 
}

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.