java - 用Java实现生产者消费者

标签 java multithreading concurrency producer-consumer

这是一篇关于生产者消费者模式的实现作业。下面的实现有什么问题。我在谷歌上搜索了各种实现,但我无法理解我的问题出在哪里。

I have a shared queue

I synchronize the producer and consumer on the same lock

实现

共享队列:

 class SharedQueue{
    public static Queue<Integer>   queue  = new LinkedList<Integer>();
 }

生产者线程:

//The producer thread
class Producer implements Runnable{
    public void run()
    {
        synchronized (SharedQueue.queue)
        {
            if(SharedQueue.queue.size() >=5)
            {
                try {
                    SharedQueue.queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Random r  = new Random();

            int x = r.nextInt(10);
            System.out.println("Inside Producer" + x);

            SharedQueue.queue.offer(x);


            SharedQueue.queue.notify();

        }
    }
}

消费者线程:

class Consumer implements  Runnable{
    public void run()
    {
        synchronized (SharedQueue.queue)
        {
            if(SharedQueue.queue.size() == 0)
            {
                try {
                    SharedQueue.queue.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
            }

            int k = SharedQueue.queue.remove();

            System.out.println("Inside consumer" + k);
        }
    }
}

主程序

public class ProducerConsumerTest {

    public static void main(String[] args)
    {
        
        Thread p = new Thread(new Producer());
        Thread q = new Thread(new Consumer());

        p.start();
        q.start();

    }
}

最佳答案

尝试替换:

if(SharedQueue.queue.size() >= 5)

与:

while(SharedQueue.queue.size() >= 5)

还有这个:

if(SharedQueue.queue.size() == 0)

与:

while(SharedQueue.queue.size() == 0)

只是为了在调用notify() 后重新检查条件。

关于java - 用Java实现生产者消费者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10274223/

相关文章:

java - 在考虑并行化外部流之前,是否会完全并行处理内部并行流?

java - 防止上传中间 Maven Artifact

Java 扫描器不读取特定文件

java - 如何解决我的构建错误?

java - 了解死锁

java - 可重入读写锁同步上是 Write Locked

scala - 在 Scala 中,为什么没有 `Future.onComplete` 的实现?

java - 是什么导致了 java.lang.ArrayIndexOutOfBoundsException 以及如何防止它?

java - 2 个 JVM 之间的低 CPU 使用率轮询架构

ios - iOS 上的 POSIX 线程