Import Java. util. arraylist; import Java. util. concurrent. executorservice; import Java. util. concurrent. executors; import Java. util. concurrent. semaphore; import Java. util. concurrent. locks. lock; import Java. util. concurrent. locks. reentrantlock;/*** four synchronization devices are added in Java 5.0 for inter-Thread process coordination. They are: * semaphore, countdownlatch, cyclicbarrier, and exchanger. * This example describes semaphore. * Semaphore is a tool used to manage a resource pool. It can be regarded as a pass. * to obtain resources from the resource pool, the thread must first get the pass. * If the thread cannot get the pass temporarily, the thread is blocked and enters the waiting state. */Public class semaphoretest {/*** the class simulating the resource pool * only issues two passes to the pool, that is, only two threads are allowed to obtain resources in the pool. */Public static class pool {// Save the resource arraylist in the resource pool <string> pool = NULL; // pass semaphore pass = NULL; lock = new reentrantlock (); public pool (INT size) {// initialize the resource pool = new arraylist <string> (); For (INT I = 0; I <size; I ++) {pool. add ("resource" + I) ;}// issue two passes pass = new semaphore (2);} Public String get () throws interruptedexception {// get the pass, the resource system can be obtained only after the pass is obtained. out. println ("try to get a pass... "); pass. acquire (); system. out. println ("got a pass"); Return getresource ();} public void put (string resource) {// return the pass and return the resource system. out. println ("released a pass"); pass. release (); releaseresource (Resource);} private string getresource () {lock. lock (); string result = pool. remove (0); system. out. println ("resource" + Result + "removed"); lock. unlock (); return result;} private void releaseresource (string resource) {lock. lock (); system. out. println ("resource" + resource + "Returned"); pool. add (Resource); lock. unlock () ;}} public static void testpool () {// resource pool final pool apool = new pool (10); runnable worker = new runnable () {public void run () {string resource = NULL; try {// obtain resourceresource = apool. get (); // use resource to do the work system. out. println ("I am working on" + Resource); thread. sleep (1, 500); system. out. println ("I finished on" + Resource);} catch (interruptedexception ex) {}// return resourceapool. put (Resource) ;}}; // start five tasks: executorservice service = executors. newcachedthreadpool (); For (INT I = 0; I <5; I ++) {service. submit (worker);} service. shutdown ();} public static void main (string [] ARGs) {semaphoretest. testpool ();}}