Semaphore thread signal light

Source: Internet
Author: User

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

}

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.