我正在研究关于 java 中的线程的生产者和消费者设计模式,我最近在 java 5 中进行了探索,介绍了 Java 5 中 BlockingQueue 数据结构的介绍 它现在更简单了,因为 BlockingQueue 通过引入阻塞方法隐式地提供了这种控制放()和取()。现在您不需要使用等待和通知来在生产者和消费者之间进行通信。BlockingQueue put() 方法将在 Bounded Queue 的情况下 Queue 已满时阻塞,如果 Queue 为空,则 take() 方法将阻塞。在下一节中,我们将看到一个生产者消费者设计模式的代码示例。我已经开发了以下程序,但也请让我知道 waut() 和 notify() 的旧式方法,我也想用旧式方法开发相同的逻辑
人们请告知如何实现这一点,经典方式是使用 wait() 和 notify() 方法在生产者和消费者线程之间进行通信,并在单个条件下阻塞它们中的每一个,例如满队列和空队列......?
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ProducerConsumerPattern {
public static void main(String args[]){
//Creating shared object
BlockingQueue sharedQueue = new LinkedBlockingQueue();
//Creating Producer and Consumer Thread
Thread prodThread = new Thread(new Producer(sharedQueue));
Thread consThread = new Thread(new Consumer(sharedQueue));
//Starting producer and Consumer thread
prodThread.start();
consThread.start();
}
}
//Producer Class in java
class Producer implements Runnable {
private final BlockingQueue sharedQueue;
public Producer(BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
for(int i=0; i<10; i++){
try {
System.out.println("Produced: " + i);
sharedQueue.put(i);
} catch (InterruptedException ex) {
Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
//Consumer Class in Java
class Consumer implements Runnable{
private final BlockingQueue sharedQueue;
public Consumer (BlockingQueue sharedQueue) {
this.sharedQueue = sharedQueue;
}
@Override
public void run() {
while(true){
try {
System.out.println("Consumed: "+ sharedQueue.take());
} catch (InterruptedException ex) {
Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Output:
Produced: 0
Produced: 1
Consumed: 0
Produced: 2
Consumed: 1
Produced: 3
Consumed: 2
Produced: 4
Consumed: 3
Produced: 5
Consumed: 4
Produced: 6
Consumed: 5
Produced: 7
Consumed: 6
Produced: 8
Consumed: 7
Produced: 9
Consumed: 8
Consumed: 9