关于java中的生产者和消费者模式与阻塞队列方法

Cra*_*ava 1 java concurrency multithreading

我正在研究与 Java 中的线程有关的生产者和消费者设计模式,我最近在 Java 5 中进行了探索,介绍了 Java 5 中引入 BlockingQueue 数据结构 现在更简单了,因为 BlockingQueue 通过引入阻塞方法隐式地提供了这种控制put() 和 take()。现在您不需要使用等待和通知在生产者和消费者之间进行通信。在有界队列的情况下,如果队列已满,则 BlockingQueue put() 方法将阻塞,如果队列为空,则 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
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 5

如果您想知道另一种方法,请尝试使用 ExecutorService

public static void main(String... args) {
    ExecutorService service = Executors.newSingleThreadExecutor();
    for (int i = 0; i < 100; i++) {
        System.out.println("Produced: " + i);

        final int finalI = i;
        service.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("Consumed: " + finalI);
            }
        });
    }
    service.shutdown();
}
Run Code Online (Sandbox Code Playgroud)

只需 10 个任务,生产者就可以在消费者开始之前完成。如果您尝试 100 个任务,您可能会发现它们是交错的。