在 Java 中,生產者-消費者模式是一種常見的同步多線程編程模式。在這個模式中,一個線程(生產者)負責生成數據,另一個線程(消費者)負責消費數據。數據在生產者和消費者之間通過一個緩存或隊列進行傳遞。
下面是一種使用wait()
和notify()
方法實現的生產者-消費者模式:
class Buffer { private int data; private boolean isEmpty = true; public synchronized void produce(int newData) { while (!isEmpty) { try { wait(); } catch (InterruptedException e) {} } data = newData; isEmpty = false; notify(); } public synchronized int consume() { while (isEmpty) { try { wait(); } catch (InterruptedException e) {} } int result = data; isEmpty = true; notify(); return result; } } class Producer implements Runnable { private Buffer buffer; public Producer(Buffer buffer) { this.buffer = buffer; } public void run() { for (int i = 0; i< 10; i++) { buffer.produce(i); } } } class Consumer implements Runnable { private Buffer buffer; public Consumer(Buffer buffer) { this.buffer = buffer; } public void run() { for (int i = 0; i< 10; i++) { int data = buffer.consume(); System.out.println("Consumed " + data); } } } public class Main { public static void main(String[] args) { Buffer buffer = new Buffer(); Thread producerThread = new Thread(new Producer(buffer)); Thread consumerThread = new Thread(new Consumer(buffer)); producerThread.start(); consumerThread.start(); } }
在這個實現中,生產者和消費者共享一個Buffer
對象。當生產者調用produce
方法時,如果緩沖區非空,生產者線程進入等待狀態,直到緩沖區為空。當生產者放置數據并更新緩沖區狀態后,它使用notify
方法通知消費者線程。消費者線程在消費數據時采取類似的行動。