Android 中 Activity 開啟 Produce 與 Customer 兩個執行緒,共享 Integer[10] 陣列。Produce 執行緒不斷寫入 1000,寫滿後等待;Customer 執行緒不斷清空陣列,清空後通知 Produce 繼續寫入;Activity 要即時刷新目前陣列的 size。
Java 方面,兩個執行緒共享一個陣列,需保證同一時刻僅一個執行緒操作,否則產生競爭;應讓一個執行緒執行時另一個處於阻塞。Android 方面,UI 主線程需即時讀取 size,子線程透過 handler 發送訊息給主線程,由主線程解析並更新顯示。
使用 ReentrantLock 搭配 notFull、notEmpty 兩個 Condition 完成阻塞與喚醒,uiHandler 負責主/子線程通訊:
public class Buffer {
private static Lock lock = new ReentrantLock();
private static Condition notEmpty = lock.newCondition();
private static Condition notFull = lock.newCondition();
private static final int CAPACITY = 10;
protected LinkedList<Integer> queue = new LinkedList<Integer>();
protected void write(int value) {
lock.lock();
try {
if (queue.size() == CAPACITY) {
Message msg = new Message();
msg.what = Definition.FULL;
ConsumerProducerActivity.uiHandler.sendMessage(msg);
notFull.await(); // 已滿,等待取走資料
}
queue.offer(value);
Message msg = new Message();
msg.what = Definition.NOTEMPTY;
ConsumerProducerActivity.uiHandler.sendMessage(msg);
notEmpty.signal(); // 非空,喚醒非空功能
} catch (InterruptedException e) { e.printStackTrace(); }
finally { lock.unlock(); }
}
protected int read() {
lock.lock();
int value = 0;
try {
if (queue.size() == 0) {
Message msg = new Message();
msg.what = Definition.Empty;
ConsumerProducerActivity.uiHandler.sendMessage(msg);
notEmpty.await(); // 等待寫入
}
value = queue.remove();
Message msg = new Message();
msg.what = Definition.NOTEMPTY;
ConsumerProducerActivity.uiHandler.sendMessage(msg);
notFull.signal(); // 取走資料,喚醒 notFull
} catch (InterruptedException e) { e.printStackTrace(); }
finally { lock.unlock(); }
return value;
}
}
亦可使用 java.util.concurrent 中的阻塞隊列 ArrayBlockingQueue、LinkBlockingQueue、PriorityBlockingQueue 實作。更多內容請見原系列文章第 2 頁。