java.util.concurrent.Semaphore这个类里面的主要方法为:
void acquire():Acquires a permit from this semaphore, blocking until one is available, or the thread isinterrupted.
boolean tryAcquire():Acquires a permit from this semaphore, only if one is available at the time of invocation.
void release(): Releases a permit, returning it to the semaphore.
//Test.java
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Semaphore;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService execSer = Executors.newCachedThreadPool();
final Semaphore sem = new Semaphore(3);
for (int i = 0; i < 12; i++) {
final int NO = i;
Runnable run = new Runnable(){
public void run() {
try {
sem.acquire();
Thread.sleep(1000);
System.out.println("Runnable :"+NO);
sem.release();
System.out.println("---"+sem.availablePermits());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
execSer.execute(run);
}
execSer.shutdown();
}
}
原文:http://www.cnblogs.com/fengfengtk/p/5978308.html