在Java中,生產者消費者模型可以通過使用線程同步機制(如synchronized關鍵字、Lock接口、Semaphore信號量等)和wait()、notifyAll()等待通知機制實現。這里給出一個簡單的示例,使用synchronized關鍵字和wait()、notifyAll()方法實現生產者消費者模型。
首先,創建一個共享資源類(共享隊列):
import java.util.LinkedList;
import java.util.Queue;
public class SharedQueue {
private Queue<Integer> queue = new LinkedList<>();
public synchronized void add(int item) {
while (queue.size() == 10) {
try {
wait(); // 當前線程等待,釋放鎖
} catch (InterruptedException e) {
e.printStackTrace();
}
}
queue.add(item);
notifyAll(); // 當前線程通知其他線程
}
public synchronized int remove() {
while (queue.isEmpty()) {
try {
wait(); // 當前線程等待,釋放鎖
} catch (InterruptedException e) {
e.printStackTrace();
}
}
int item = queue.poll();
notifyAll(); // 當前線程通知其他線程
return item;
}
}
接下來,創建生產者和消費者線程類:
public class Producer implements Runnable {
private SharedQueue sharedQueue;
public Producer(SharedQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
sharedQueue.add(i);
System.out.println("生產者生產了: " + i);
try {
Thread.sleep(100); // 模擬生產耗時
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Consumer implements Runnable {
private SharedQueue sharedQueue;
public Consumer(SharedQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
int item = sharedQueue.remove();
System.out.println("消費者消費了: " + item);
try {
Thread.sleep(200); // 模擬消費耗時
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
最后,在主類中創建生產者和消費者線程并啟動:
public class Main {
public static void main(String[] args) {
SharedQueue sharedQueue = new SharedQueue();
Producer producer = new Producer(sharedQueue);
Consumer consumer = new Consumer(sharedQueue);
Thread producerThread = new Thread(producer);
Thread consumerThread = new Thread(consumer);
producerThread.start();
consumerThread.start();
}
}
運行上述代碼,可以看到生產者和消費者線程交替執行,生產者生產商品放入共享隊列,消費者從共享隊列取出商品。這樣就實現了一個簡單的生產者消費者模型。