編輯:關於 Android 程式設計
Java 的並發工具在 Java 5 之後有了一次大躍進,java.util.concurrent 把過去需要手動 wait/notify 才能解決的問題,變成幾行程式碼就能搞定。本文依序梳理執行緒的建立、同步互斥、執行緒間通訊、執行緒池,以及 Lock、Condition、Semaphore、CyclicBarrier、CountDownLatch、Exchanger 與阻塞佇列這些工具的用途。
new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}.start();
new Thread(new Runnable() {
public void run() {
while (true) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
}).start();
public class TimerTest {
public static void main(String[] args) {
ScheduledExecutorService service = Executors.newScheduledThreadPool(3);
service.scheduleAtFixedRate(new Runnable() {
public void run() {
System.out.println(Thread.currentThread().getName());
}
}, 10, 1, TimeUnit.SECONDS);
}
}
經典範例:子執行緒印 10 次、主執行緒印 100 次,交替進行。
public class TeaTSynchronized {
static Business business = new Business();
public static void main(String[] args) throws InterruptedException {
init(); // 啟動子執行緒
for (int i = 0; i < 50; i++) {
business.main(); // 主執行緒
}
}
private static void init() {
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 50; i++) {
try {
business.sub();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}
class Business {
boolean shouldSub = true;
// 子執行緒
public synchronized void sub() throws InterruptedException {
// 這裡刻意用 while 而非 if,防止虚假喚醒
while (!shouldSub) {
wait();
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " count " + i);
}
shouldSub = false;
notify();
}
// 主執行緒
public synchronized void main() throws InterruptedException {
while (shouldSub) {
wait();
}
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " count " + i);
}
shouldSub = true;
notify();
}
}
這裡有兩個容易被打叉的細節:一是必須用 while 而非 if 檢查條件,因為虚假喚醒(spurious wakeup)在規範上是允許的;二是 notify() 的呼叫必須在同步區塊內,否則會丟出 IllegalMonitorStateException。
ThreadLocal 可以想成一個 Map:每個執行緒往裡頭放一份自己的資料,彼此互不干擾;而在同一個執行緒的不同程式碼區塊之間,資料則是共享的。一個 ThreadLocal 變數對單一執行緒來說只對應一份值。
ThreadLocal,讓每個執行緒擁有一份獨立副本。若需要原子性的計數,直接用 AtomicInteger;陣列則用 AtomicIntegerArray,省去自己寫 lock。
public class ThreadPool {
public static void main(String[] args) {
// 快取型:可依需求彈性增減
// ExecutorService cached = Executors.newCachedThreadPool();
// 單一執行緒:前一個結束後才啟動下一個
// ExecutorService single = Executors.newSingleThreadScheduledExecutor();
// 固定大小
ExecutorService pool = Executors.newFixedThreadPool(4);
pool.execute(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " 任務:" + i);
}
}
});
pool.shutdown(); // 任務收尾後關閉
}
}
ExecutorService single = Executors.newSingleThreadExecutor();
Future<String> future = single.submit(new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(1000);
return "hello world";
}
});
try {
System.out.println("result: " + future.get(3, TimeUnit.SECONDS));
} catch (Exception e) {
e.printStackTrace();
}
submit() 回傳的 Future 讓你能在需要的時候用 get() 取回結果,還可以帶上逾時時間避免無限等待。
class Business {
private int count = 0;
Lock lock = new ReentrantLock();
public void service() {
lock.lock();
try {
count++;
Thread.sleep(10);
System.out.println(count);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock(); // 一定要放 finally,否則死鎖
}
}
}
讀寫鎖的規則是「讀互不排斥、寫互斥」:
public Object getEntityFromCache(String key) {
Object object = cache.get(key);
if (object == null) {
lock.readLock().lock();
try {
object = "btbu"; // 這裡應該去資料庫查
cache.put(key, object);
} finally {
lock.readLock().unlock();
}
}
return object;
}
Condition 將 Object 的監視器方法(wait、notify、notifyAll)拆解成獨立物件,可與任意 Lock 實作搭配,為每個物件提供各自的等待集合(wait-set)。Lock 取代了 synchronized 的角色,Condition 則取代了監視器方法的角色。
class Business {
boolean shouldSub = true;
ReentrantLock lock = new ReentrantLock();
Condition condition = lock.newCondition();
public void sub() throws InterruptedException {
lock.lock();
try {
while (!shouldSub) {
condition.await(); // 同樣用 while 防虚假喚醒
}
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " count " + i);
}
shouldSub = false;
} finally {
condition.signal();
}
}
public void main() throws InterruptedException {
lock.lock();
try {
while (shouldSub) {
condition.await();
}
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " count " + i);
}
shouldSub = true;
} finally {
condition.signal();
}
}
}
這是 Condition 最經典的應用:用 notFull 與 notEmpty 兩個條件變數,就能讓生產者與消費者精準地互相等待。
class BoundedBuffer {
final Lock lock = new ReentrantLock();
final Condition notFull = lock.newCondition();
final Condition notEmpty = lock.newCondition();
final Object[] items = new Object[100];
int putptr, takeptr, count;
public void put(Object x) throws InterruptedException {
lock.lock();
try {
while (count == items.length) {
notFull.await(); // 滿了,生產者等
}
items[putptr] = x;
if (++putptr == items.length) putptr = 0;
++count;
notEmpty.signal(); // 通知消費者有貨了
} finally {
lock.unlock();
}
}
public Object take() throws InterruptedException {
lock.lock();
try {
while (count == 0) {
notEmpty.await(); // 空了,消費者等
}
Object x = items[takeptr];
if (++takeptr == items.length) takeptr = 0;
--count;
notFull.signal(); // 通知生產者有位子了
return x;
} finally {
lock.unlock();
}
}
}
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Semaphore sp = new Semaphore(3); // 同時最多 3 個
for (int i = 0; i < 10; i++) {
service.execute(new Runnable() {
public void run() {
try {
sp.acquire();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 進入,當前已有 " + (3 - sp.availablePermits()) + " 個並發");
try {
Thread.sleep((long) (Math.random() * 10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
sp.release();
}
});
}
}
}
典型用途是限制資料庫連線數、控制同時下載的檔案數。要注意「離開」的訊息若與 release 沒有放在同一個原子區塊,印出來的並發數可能不準確。
當一組固定數量的執行緒需要不時在共同的柵欄點會合時,CyclicBarrier 就非常合適。屏障釋放等待中的執行緒後可以重複使用,所以稱為「循環」的 barrier。
public class CyclicBarrierTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CyclicBarrier cb = new CyclicBarrier(3);
for (int i = 0; i < 3; i++) {
service.execute(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 即將到達集合點 1,已有 " + cb.getNumberWaiting() + " 個在等");
cb.await();
Thread.sleep((long) (Math.random() * 10000));
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 即將到達集合點 2,已有 " + cb.getNumberWaiting() + " 個在等");
cb.await();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
service.shutdown();
}
}
以給定的計數初始化,每呼叫一次 countDown() 就減一;計數歸零之前,await() 會一直阻塞,歸零後所有等待的執行緒一併釋放。這種行為只發生一次,計數無法重置。
public class CountdownLatchTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final CountDownLatch cdOrder = new CountDownLatch(1); // 命令閘門
final CountDownLatch cdAnswer = new CountDownLatch(3); // 等 3 個回覆
for (int i = 0; i < 3; i++) {
service.execute(new Runnable() {
public void run() {
try {
System.out.println("執行緒 " + Thread.currentThread().getName() + " 準備接受命令");
cdOrder.await();
System.out.println("執行緒 " + Thread.currentThread().getName() + " 已接受命令");
Thread.sleep((long) (Math.random() * 10000));
System.out.println("執行緒 " + Thread.currentThread().getName() + " 回報結果");
cdAnswer.countDown();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
try {
Thread.sleep((long) (Math.random() * 10000));
System.out.println("主執行緒即將發布命令");
cdOrder.countDown();
System.out.println("命令已送出,等待所有回覆");
cdAnswer.await();
System.out.println("已收到全部回覆");
} catch (Exception e) {
e.printStackTrace();
}
service.shutdown();
}
}
和 CyclicBarrier 的差異要記牢:CyclicBarrier 等的是「同批執行緒到齊」,可重複使用;CountDownLatch 等的是「一堆任務計數歸零」,只能用一次。
Exchanger 是一個同步點,讓兩個執行緒在此交換手上的物件:各自呼叫 exchange() 把自己的資料交出去,同時收到對方的資料。它可以視為 SynchronousQueue 的雙向版本,在遺傳演算法、_pipeline 設計等場景很實用。
public class ExchangerTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final Exchanger<String> exchanger = new Exchanger<>();
service.execute(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
String data1 = "zxx";
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 正在把 " + data1 + " 換出去");
String data2 = exchanger.exchange(data1);
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 換回 " + data2);
} catch (Exception e) {
e.printStackTrace();
}
}
});
service.execute(new Runnable() {
public void run() {
try {
Thread.sleep((long) (Math.random() * 10000));
String data1 = "lhm";
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 正在把 " + data1 + " 換出去");
String data2 = exchanger.exchange(data1);
System.out.println("執行緒 " + Thread.currentThread().getName()
+ " 換回 " + data2);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
前面用兩個 Condition 辛苦實作的有界緩衝區,用 ArrayBlockingQueue 幾行就能取代——put 在滿時自動等待,take 在空時自動等待。
public class BlockingQueueCondition {
public static void main(String[] args) {
ExecutorService service = Executors.newSingleThreadExecutor();
final Business3 business = new Business3();
service.execute(new Runnable() {
public void run() {
for (int i = 0; i < 50; i++) {
business.sub();
}
}
});
for (int i = 0; i < 50; i++) {
business.main();
}
}
}
class Business3 {
BlockingQueue<Integer> subQueue = new ArrayBlockingQueue<>(1);
BlockingQueue<Integer> mainQueue = new ArrayBlockingQueue<>(1);
{
// 匿名初始化區塊,每建立一個物件就執行一次
try {
mainQueue.put(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void sub() {
try {
mainQueue.take();
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
subQueue.put(1);
} catch (Exception e) {
e.printStackTrace();
}
}
public void main() {
try {
subQueue.take();
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
mainQueue.put(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java 5 之後併入了 java.util.concurrent 這個並發工具庫,其中也包含 thread-safe 版本的集合實作。幾個容易混淆的基礎觀念:
HashSet 只有 key,底層其實是 HashMap,只是不使用 value 那部分。HashMap 是 key-value 的雙列表結構。ConcurrentModificationException;需要邊走邊刪時,改用迭代器的 remove() 或 CopyOnWriteArrayList 這類方案。AtomicIntegerReentrantLockReentrantReadWriteLockArrayBlockingQueue(有界)或 LinkedBlockingQueueSemaphoreCountDownLatchCyclicBarrierExchanger
Toolbar + DrawerLayout 實戰詳解
近來也想研究一下 Toolbar + DrawerLayout 的用法,參考網上前輩們的實作,我把大部分效果都跑了一遍,現在記錄各功能的實現步驟與一些細節注意點。 如上
ListView 源碼深度解析:復用機制全流程
前言 雖然 RecyclerView 問世已久、ListView 看似過時,但它有許多優秀的思想仍值得細細品味。提到 ListView,大家第一反應就是復用機制。這裡不再
Android 呼叫相機與相簿取圖並裁切成頭像的完整流程
先講思路:Android 系統本身就內建了圖片裁切應用,因此我們只要把照片交給它,再把裁切好的結果取回自己的畫面顯示即可,不必自己實作裁剪 UI。 在許多 App 中都有
Android 實戰:為你的 App 接入 mob 短信驗證碼功能
一、前言 如今幾乎每個 App 都離不開短信能力,無論是用戶註冊還是消息通知,往往都要發一條短信出去。但對個人開發者而言,直接購買第三方短信服務的成本著實不低。好在 mo