Reproduced in: http://janeky.iteye.com/blog/769965
Let's start by learning more about this class in the JDK1.5 API:
"A count semaphore. Conceptually, semaphores maintain a set of licenses. If necessary, block each acquire () before the license is available, and then obtain the license. Each release () adds a license that may release a blocked fetch. However, instead of using the actual license object, Semaphore only counts the number of available licenses and takes action accordingly. ”
We typically use it to control an object's thread access to an object
For example, for a container, we specify that only n threads can operate at the same time
Using semaphores to simulate implementation
Package Com.winterbe.java8.samples.concurrent;import Java.util.collections;import Java.util.hashset;import Java.util.random;import Java.util.set;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import java.util.concurrent.semaphore;/* * Semaphore typically used for object pooling control * */public class Testsemaphore {public static void main (string[] args) throws interruptedexception {Executorservice exec = Executors.newca Chedthreadpool (); Testsemaphore t = new Testsemaphore (); final boundedhashset<string> set = T.getset (); final int max=10;for (int i = 0; i < MAX; i++) {//10 threads simultaneous Operation Addexec.execute (new Runnable () {public void run () {try {set. Deal (Thread.CurrentThread (). GetName ());} catch (Interruptedexception e) {e.printstacktrace ();}}});} Exec.shutdown ();} Public boundedhashset<string> Getset () {return new boundedhashset<string> (2);//define a thread with a boundary constraint of 2}class boundedhashset<t> {Private final set<t> set;private final Semaphore semaphore;final Random RANdom = new Random ();p ublic boundedhashset (int bound) {This.set = Collections.synchronizedset (New hashset<t> ()); This.semaphore = new Semaphore (bound, true);} public void Deal (T o) throws interruptedexception {System.out.println ("Availablepermits:" +semaphore.availablepermits ()); Semaphore.acquire ();//Semaphore controls the number of threads that can be accessed, and if the number of accesses reaches Bount, Set.add (o) is blocked; System.out.printf ("add:%s%n", O); Thread.Sleep (random.nextint);//sleep after a certain amount of time, Master signal, here is the business logic processing Time semaphore.release (); Release the semaphore System.out.printf ("remove:%s%n", O); }}
Summary: Semaphore is typically used for object pooling control
Java Multithreaded Learning-java.util.concurrent details (iii) Semaphore