Java Semaphore Implementation:
Semaphore is currently used in multi-threaded environments, the operating system semaphore is a very important concept, in the process of control has been applied. The semaphore of the Java Concurrency Library makes it easy to control the semaphore, Semaphore can control the number of simultaneous accesses to a resource, obtain a license through acquire (), and release () releases a license if there is no waiting. For example, under Windows, you can set the maximum number of client accesses for a shared file.
PackageCom.multithread.semaphore;ImportJava.util.concurrent.Semaphore;ImportCom.multithread.main.ExampleInterface;/*** Semaphore can control the number of simultaneous use of a resource. * Get permission through acquire (), no wait. * Release () releases a license. * * */ Public classSemaphoreexampleextendsexampleinterface{FinalSemaphore SEMA =NewSemaphore (1); intG_num = 0; @Override Public voidStartdemo () { for(inti=0;i<10;i++) {Thread se=NewSemamultithread (I,sema); Se.start (); }} @Override Public voidStartDemo2 () {FinalSemaphore _lsema =NewSemaphore (10); for(inti=0;i<50;i++) {Thread se=NewSemamultithread (I,_lsema); Se.start (); } } classSemamultithreadextendsThread {intindex =-1; Semaphore Msema=NULL; PublicSemamultithread (intI,semaphore SE) { This. index =i; Msema=se; } @Override Public voidrun () {Try{msema.acquire (); System.out.println ("Index:" + This. Index); Thread.Sleep ((Long) (Math.random () *100)); Msema.release (); System.out.println ("----------------:"+msema.availablepermits ()); Thread.Sleep ((Long) (Math.random () *100)); } Catch(interruptedexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } } }}
You can make each thread mutually exclusive: final Semaphore sema = new Semaphore (1);
New Semaphore (ten); At the same time, the maximum of 10 threads is running, similar to the effect of a thread pool!
Seconds to kill multithreading eighth classic thread sync semaphore semaphore (cont.)