Java模擬生產(chǎn)者和消費者是一個非常經(jīng)典的多線程編程問題。生產(chǎn)者負責生產(chǎn)數(shù)據(jù)并將其添加到一個共享隊列中,消費者則從隊列中獲取數(shù)據(jù)并進行處理。以下是使用Java多線程實現(xiàn)生產(chǎn)者和消費者的示例代碼:
public class Producer implements Runnable { private final Queuequeue; private final int maxSize; public Producer(Queue queue, int maxSize) { this.queue = queue; this.maxSize = maxSize; } @Override public void run() { int i = 0; while (true) { synchronized (queue) { while (queue.size() == maxSize) { try { System.out.println("隊列已滿,生產(chǎn)者線程等待"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("生產(chǎn)者線程向隊列中加入了數(shù)據(jù)" + i); queue.offer(i++); queue.notifyAll(); } } } } public class Consumer implements Runnable { private final Queue queue; public Consumer(Queue queue) { this.queue = queue; } @Override public void run() { while (true) { synchronized (queue) { while (queue.isEmpty()) { try { System.out.println("隊列為空,消費者線程等待"); queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int x = queue.poll(); System.out.println("消費者線程從隊列中取出了數(shù)據(jù)" + x); queue.notifyAll(); } } } } public class Main { public static void main(String[] args) { Queue queue = new LinkedList<>(); int maxSize = 10; Producer producer = new Producer(queue, maxSize); Consumer consumer = new Consumer(queue); Thread producerThread = new Thread(producer); Thread consumerThread = new Thread(consumer); producerThread.start(); consumerThread.start(); } }
以上代碼中使用了一個共享的隊列來模擬生產(chǎn)者和消費者之間的數(shù)據(jù)傳輸。當隊列滿時,生產(chǎn)者線程會調(diào)用wait()方法進行等待;當隊列為空時,消費者線程會調(diào)用wait()方法進行等待。當隊列有更新時,生產(chǎn)者和消費者線程都會調(diào)用notifyAll()方法來通知等待中的線程。