Semaphore is a count semaphore. In terms of concept, semaphores maintain a license set. If necessary, eachAcquire ()And then obtain the license. EachRelease ()Add a license to release a blocked recipient. However, do not use the actual license object,SemaphoreOnly the available license numbers are counted and corresponding actions are taken. Semaphore is usually used to limit the number of threads that can access certain resources (physical or logical.
Small instance:
Import java. util. Concurrent. executorservice;
Import java. util. Concurrent. executors;
Import java. util. Concurrent. semaphore;
/**
* Signal lights in the concurrent Library
* @ Author yangbaobao
*
*/
Public class semaphoredemo {
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
Executorservice pool = executors. newcachedthreadpool ();
Final semaphore light = new semaphore (3 );
For (INT I = 0; I <10; I ++ ){
Final int Index = I;
Pool.exe cute (New thread (New runnable (){
Public void run (){
Try {
Light. Acquire (1 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
Try {
Thread. currentthread (). Sleep (1000 );
} Catch (interruptedexception e ){
// Todo auto-generated Catch Block
E. printstacktrace ();
}
System. Out. println (thread. currentthread (). getname () + "" + index );
Light. Release ();
}
}));
}
}
}