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 ();
}
}