import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreTest1 {
private static final int SEM_MAX = 10;
public static void main(String[] args) {
Semaphore sem = new Semaphore(SEM_MAX);
//創建線程池
ExecutorService threadPool = Executors.newFixedThreadPool(3);
//在線程池中執行任務
threadPool.execute(new MyThread(sem, 5));
threadPool.execute(new MyThread(sem, 4));
threadPool.execute(new MyThread(sem, 7));
//關閉池
threadPool.shutdown();
}
}
class MyThread extends Thread {
private volatile Semaphore sem; // 信號量
private int count; // 申請信號量的大小
MyThread(Semaphore sem, int count) {
this.sem = sem;
this.count = count;
}
public void run() {
try {
// 從信號量中獲取count個許可
sem.acquire(count);
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " acquire count="+count);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
// 釋放給定數目的許可,將其返回到信號量。
sem.release(count);
System.out.println(Thread.currentThread().getName() + " release " + count + "");
}
}
}
pool-1-thread-1 acquire count=5
pool-1-thread-2 acquire count=4
pool-1-thread-1 release 5
pool-1-thread-2 release 4
pool-1-thread-3 acquire count=7
pool-1-thread-3 release 7
結果說明:信號量sem的許可總數是10個;共3個線程,分別需要獲取的信號量許可數是5,4,7。前面兩個線程獲取到信號量的許可后,sem中剩余的可用的許可數是1;因此,最后一個線程必須等前兩個線程釋放了它們所持有的信號量許可之后,才能獲取到7個信號量許可。
Semaphore是一個計數信號量,它的本質是一個"共享鎖"。
信號量維護了一個信號量許可集。線程可以通過調用acquire()來獲取信號量的許可;當信號量中有可用的許可時,線程能獲取該許可;否則線程必須等待,直到有可用的許可為止。 線程可以通過release()來釋放它所持有的信號量許可。