Copy Code code as follows:
Package Com.yao;
Import Java.util.concurrent.ExecutorService;
Import java.util.concurrent.Executors;
Import Java.util.concurrent.Semaphore;
/**
* Java 5.0 adds 4 synchronization devices that coordinate the process between threads, respectively:
* Semaphore, Countdownlatch, Cyclicbarrier and exchanger.
* This example mainly introduces semaphore.
* Semaphore is a tool used to manage a resource pool and can be viewed as a pass,
* Threads to get resources from the resource pool must first get the pass,
* If the thread cannot get the pass temporarily, the thread will be blocked into the waiting state.
*/
public class Mysemaphore extends Thread {
private int i;
Private semaphore semaphore;
Public Mysemaphore (int i,semaphore semaphore) {
THIS.I = i;
This.semaphore = semaphore;
}
public void Run () {
if (semaphore.availablepermits () > 0) {
System.out.println ("" "+i+" has vacancy: ");
}else{
System.out.println ("" +i+ "waiting, no Vacancy");
}
try {
Semaphore.acquire ();
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("" +i+ "to get Vacant");
try {
Thread.Sleep ((int) math.random () *10000);
catch (Interruptedexception e) {
E.printstacktrace ();
}
System.out.println ("" +i+ "use complete");
Semaphore.release ();
}
public static void Main (string[] args) {
Semaphore semaphore = new semaphore (2);
Executorservice service = Executors.newcachedthreadpool ();
for (int i = 0; i<10 i++) {
Service.execute (New Mysemaphore (I,semaphore));
}
Service.shutdown ();
semaphore.acquireuninterruptibly (2);
SYSTEM.OUT.PRINTLN ("Use completed, need to clean up");
Semaphore.release (2);
}
}