import java.util.ArrayList;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;/** * Java 5.0裡新加了4個協調線程間進程的同步裝置,它們分別是: * Semaphore, CountDownLatch, CyclicBarrier和Exchanger. * 本例主要介紹Semaphore。 * Semaphore是用來管理一個資源集區的工具,可以看成是個通行證, * 線程要想從資源集區拿到資源必須先拿到通行證, * 如果線程暫時拿不到通行證,線程就會被阻斷進入等待狀態。 */public class SemaphoreTest {/** * 類比資源集區的類 * 只為池發放2個通行證,即同時只允許2個線程獲得池中的資源。 */public static class Pool {// 儲存資源集區中的資源ArrayList<String> pool = null;// 通行證Semaphore pass = null;Lock lock = new ReentrantLock();public Pool(int size) {// 初始化資源集區pool = new ArrayList<String>();for (int i = 0; i < size; i++) {pool.add("Resource " + i);}// 發放2個通行證pass = new Semaphore(2);}public String get() throws InterruptedException {// 擷取通行證,只有得到通行證後才能得到資源System.out.println("Try to get a pass...");pass.acquire();System.out.println("Got a pass");return getResource();}public void put(String resource) {// 歸還通行證,並歸還資源System.out.println("Released a pass");pass.release();releaseResource(resource);}private String getResource() {lock.lock();String result = pool.remove(0);System.out.println("資源 " + result + " 被取走");lock.unlock();return result;}private void releaseResource(String resource) {lock.lock();System.out.println("資源 " + resource + " 被歸還");pool.add(resource);lock.unlock();} }public static void testPool() {// 準備10個資源的資源集區final Pool aPool = new Pool(10);Runnable worker = new Runnable() {public void run() {String resource = null;try {//取得resourceresource = aPool.get();//用resource做工作System.out.println("I am working on " + resource);Thread.sleep(500);System.out.println("I finished on " + resource);} catch (InterruptedException ex) {}//歸還resourceaPool.put(resource);}};// 啟動5個任務ExecutorService service = Executors.newCachedThreadPool();for (int i = 0; i < 5; i++) {service.submit(worker);}service.shutdown();} public static void main(String[] args) {SemaphoreTest.testPool();}}