?? semaphoretest.java
字號:
package book.j2se5.thread;
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 {
//取得resource
resource = aPool.get();
//用resource做工作
System.out.println("I am working on " + resource);
Thread.sleep(500);
System.out.println("I finished on " + resource);
} catch (InterruptedException ex) {
}
//歸還resource
aPool.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();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -