在Java中,可以使用wait()
和notify()
或notifyAll()
方法來實現生產者-消費者模式。這些方法是Object
類的一部分,用于線程間的通信。下面是一個簡單的生產者-消費者模式示例:
public class Buffer {
private int data;
private boolean empty = true;
public synchronized void put(int data) {
while (!empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.data = data;
empty = false;
notifyAll();
}
public synchronized int get() {
while (empty) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
empty = true;
notifyAll();
return data;
}
}
public class Producer implements Runnable {
private Buffer buffer;
public Producer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("Produced: " + i);
buffer.put(i);
}
}
}
public class Consumer implements Runnable {
private Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
int data = buffer.get();
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();
}
}
運行上述代碼,你將看到生產者和消費者線程交替執行,生產者將數據放入緩沖區,消費者從緩沖區中取出數據。這就是一個簡單的生產者-消費者模式實現。