- 【日】結城浩 著
- 侯振龍 楊文軒 譯
- 源碼地址點擊”隨書下載“
第1章 Single Threaded Excution 模式 ——通過這座橋的只有一個人
java.util.concurrent.Semaphore (計數信號量)P53
使用場景
確保某個區域”最多隻能由N個線程“執行。
注意事項
semaphore的acquire方法和release方法必須成對調用
示例
import java.util.Random;
import java.util.concurrent.Semaphore;
class Log {
public static void println(String s) {
System.out.println(Thread.currentThread().getName() + ": " + s);
}
}
// 資源個數有限
class BoundedResource {
private final Semaphore semaphore;
private final int permits;
private final static Random random = new Random(314159);
// 構造函數(permits爲資源個數)
public BoundedResource(int permits) {
this.semaphore = new Semaphore(permits);
this.permits = permits;
}
// 使用資源
public void use() throws InterruptedException {
semaphore.acquire();
try {
doUse();
} finally {
semaphore.release();
}
}
// 實際使用資源(此處僅使用Thread.sleep)
protected void doUse() throws InterruptedException {
Log.println("BEGIN: used = " + (permits - semaphore.availablePermits()));
Thread.sleep(random.nextInt(500));
Log.println("END: used = " + (permits - semaphore.availablePermits()));
}
}
// 使用資源的線程
class UserThread extends Thread {
private final static Random random = new Random(26535);
private final BoundedResource resource;
public UserThread(BoundedResource resource) {
this.resource = resource;
}
public void run() {
try {
while (true) {
resource.use();
Thread.sleep(random.nextInt(3000));
}
} catch (InterruptedException e) {
}
}
}
public class Main {
public static void main(String[] args) {
// 設置3個資源
BoundedResource resource = new BoundedResource(3);
// 10個線程使用資源
for (int i = 0; i < 10; i++) {
new UserThread(resource).start();
}
}
}
第2章 Immutable模式——想破壞也破壞不了
使用copy-on-write的java.util.concurrent.CopyOnWriteArrayList類 P75
- CopyOnWriteArrayList類是採用copy-on-write技術來避免讀寫衝突的。
- copy-on-write,就是”寫時複製“的意思。如果使用copy-on-write,但對集合執行”寫“操作時,內部已確保安全的數組就會被整體複製。複製之後,就無需在使用迭代器依次讀取元素時擔心元素會被修改了。
- 使用copy-on-write時,每次執行”寫“操作都會執行復制。因此如果寫操作比較少,而讀操作頻率非常高時,使用時非常棒的。