The code copy is as follows:
package com.yao;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* 4 new synchronization devices for coordinating inter-thread processes are added in Java 5.0, which are:
* Semaphore, CountDownLatch, CyclicBarrier and Exchanger.
* This example mainly introduces Semaphore.
* Semaphore is a tool used to manage a resource pool, which can be regarded as a pass.
* If a thread wants to obtain resources from the resource pool, it must first obtain a pass.
* If the thread cannot get the pass temporarily, the thread will be blocked and entered a 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+"There are spaces available: ");
}else{
System.out.println(""+i+"wait, no space");
}
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+i+"get empty space");
try {
Thread.sleep((int)Math.random()*10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+i+"completely used");
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("Used, need to be cleaned");
semaphore.release(2);
}
}