Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Java 多執行緒與並發工具庫全解:從 synchronized 到 Exchanger

編輯:關於 Android 程式設計

Java 的並發工具在 Java 5 之後有了一次大躍進,java.util.concurrent 把過去需要手動 wait/notify 才能解決的問題,變成幾行程式碼就能搞定。本文依序梳理執行緒的建立、同步互斥、執行緒間通訊、執行緒池,以及 Lock、Condition、Semaphore、CyclicBarrier、CountDownLatch、Exchanger 與阻塞佇列這些工具的用途。

一、建立與啟動執行緒的兩種傳統方式

繼承 Thread

new Thread() {
    public void run() {
        while (true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
        }
    }
}.start();

實作 Runnable

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);
    }
}

三、synchronized 做同步互斥

經典範例:子執行緒印 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:資料在同一執行緒內共享

ThreadLocal 可以想成一個 Map:每個執行緒往裡頭放一份自己的資料,彼此互不干擾;而在同一個執行緒的不同程式碼區塊之間,資料則是共享的。一個 ThreadLocal 變數對單一執行緒來說只對應一份值。

五、多執行緒存取共享資料的三種套路

  1. 把需要共享的資料交給 Runnable 實作,讓多個執行緒操作同一個物件。
  2. 把共享資料封裝成一個獨立物件,多個執行緒各自持有該物件的參考。
  3. 使用 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();   // 任務收尾後關閉
    }
}

七、Callable 與 Future:可以回傳結果的執行緒

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() 取回結果,還可以帶上逾時時間避免無限等待。

八、Lock:比 synchronized 更物件導向的鎖

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:把 wait/notify 拆成多組等待集合

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 實作有界緩衝佇列

這是 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();
        }
    }
}

十、Semaphore:控制同時進入的數量

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:一組執行緒互相等待到齊

當一組固定數量的執行緒需要不時在共同的柵欄點會合時,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();
    }
}

十二、CountDownLatch:等所有任務都完成

以給定的計數初始化,每呼叫一次 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:兩兩配對交換資料

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();
                }
            }
        });
    }
}

十四、阻塞佇列:用 BlockingQueue 取代手寫條件變數

前面用兩個 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 這類方案。

選型速查

  • 只是要計數或累加 → AtomicInteger
  • 要互斥且需要可中斷、超時、公平鎖 → ReentrantLock
  • 讀多寫少 → ReentrantReadWriteLock
  • 生產者消費者 → ArrayBlockingQueue(有界)或 LinkedBlockingQueue
  • 限制同時併發數 → Semaphore
  • 等所有子任務完成再繼續 → CountDownLatch
  • 分批執行緒階段性會合 → CyclicBarrier
  • 兩個執行緒交換資料 → Exchanger
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved