Semaphore is the Concurrency tool class under the Java.util.concurrent package.
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire () blocks if necessary until a permit are available, and then takes it. Each release () adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects is used; The semaphore just keeps a count of the number available and acts accordingly. Semaphores is often used to restrict the number of threads than can access some (physical or logical) resource.
The general meaning is that semaphore can hold a license, which can be specified at initialization time, execute once acquire (), get a license, a thread enters, and when the license is 0, the thread is no longer allowed to enter, and the release releases a license once.
PackageCom.smikevon.concurrent.tools;ImportJava.util.Random;ImportJava.util.concurrent.Semaphore;/*** @description: There are a,b,c three threads, a thread output A, b thread output B, c thread output c. Requirements, start three threads at the same time, output ABC sequentially, Loop 10 times* @date: September 17, 2014 PM 8:23:05*/ Public classTestsemaphore { Public Static voidMain (string[] args) {FinalSemaphore SA =NewSemaphore (1); FinalSemaphore SB =NewSemaphore (0); FinalSemaphore sc =NewSemaphore (0); FinalRandom random =NewRandom (System.currenttimemillis ()); NewThread (NewRunnable () { Public voidrun () {Try { while(true) {Thread.Sleep (Random.nextint (3000)); Sa.acquire (); Doing (A); Sb.release (); } } Catch(interruptedexception e) {e.printstacktrace (); } } },"Thread A"). Start (); NewThread (NewRunnable () { Public voidrun () {Try { while(true) {Thread.Sleep (Random.nextint (3000)); Sb.acquire (); Doing (B); Sc.release (); } } Catch(interruptedexception e) {e.printstacktrace (); } } },"Thread B"). Start (); NewThread (NewRunnable () { Public voidrun () {Try { while(true) {Thread.Sleep (Random.nextint (3000)); Sc.acquire (); Doing (C); Sa.release (); } } Catch(interruptedexception e) {e.printstacktrace (); } } },"Thread C"). Start (); } /*** @Description: Print the name of the outgoing thread *@parammsg * @returType: void*/ Public Static voiddoing (String msg) {System.out.println (Thread.CurrentThread (). GetName ()+":"+msg); }}
Use Java Semaphore (semaphore) to rotate threads to print