java生产者消费者模型

Posted zheng123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java生产者消费者模型相关的知识,希望对你有一定的参考价值。

package javalearn;

import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumer 
    private static final int MAX = 5;

    ///////////////生产者
    public static class Producer extends Thread
        private Queue<Integer> queue;
        int i=0;
        String name;
        int max;
        public Producer(Queue<Integer> queue,String name,int max)
            super(name);
            this.queue = queue;
            this.name = name;
            this.max = max;
        

        @Override
        public void run() 
            while (true)
                synchronized(queue)
                    while (queue.size()==max)  //停产 自旋,防止出现虚假唤醒
                        try 
                            queue.wait();
                        catch (Exception e)
                            e.printStackTrace();
                        
                    
                    //继续生产
                    queue.offer(i++);
                    queue.notifyAll();
                
            
        
    
    ///////////////消费者
    public static class Consumer extends Thread
        private Queue<Integer> queue;
        String name;
        public Consumer(Queue<Integer>queue,String name)
            super(name);
            this.name = name;
            this.queue = queue;
        

        @Override
        public void run() 
            while (true)
                synchronized(queue)
                    while (queue.isEmpty())    //空了就要停
                        try 
                            queue.wait();
                        catch (Exception e)
                            e.printStackTrace();
                        
                    
                    queue.poll();
                    queue.notifyAll();
                
            
        
    
    public static void main(String[] args)
        Queue<Integer>queue = new LinkedList<>();
        Thread producer1 = new Producer(queue,"P-1",MAX);
        Thread producer2 = new Producer(queue,"P-2",MAX);
        Thread consumer1 = new Consumer(queue,"C-1");
        Thread consumer2 = new Consumer(queue,"C-2");
        producer1.start();
        producer2.start();
        consumer1.start();
        consumer2.start();
    

 

以上是关于java生产者消费者模型的主要内容,如果未能解决你的问题,请参考以下文章

Java完成生产者消费者模型

生产者消费者模型Java实现

java并发之生产者消费者模型

java生产者消费者模型

Java实现生产者-消费者模型

Java多线程:生产者消费者模型