0
点赞
收藏
分享

微信扫一扫

【2022初春】【笔记】生产者消费者问题

迪莉娅1979 2022-04-14 阅读 216
java

生产者消费者模式,是通过一个容器来解决生产者和消费者之间的强耦合关系。生产者和消费者之间不直接通信,而是通过阻塞队列进行通信。
锁在函数/while循环外,是对象锁,一个生产者/消费者持续工作。锁在while内,用户随机获取线程。

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

public class pac {
    Queue<Integer> queue = new LinkedList<>();
    final int maxsize = 10;
    class Producer extends Thread{
        @Override
        public void run(){producer();}
        public void producer(){
            while(true){
                synchronized (queue){
                    while(queue.size()==maxsize){
                        queue.notifyAll();
                        System.out.println(this.getName()+"当前队列满");
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.add(1);
                    queue.notify();
                    System.out.println(this.getName()+"生产者生产一条任务,当前队列长度为" + queue.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    class Consumer extends Thread{
        @Override
        public void run(){consumer();}
        public void consumer(){
            while(true){
                synchronized (queue){
                    while(queue.size()==0){
                        queue.notifyAll();
                        System.out.println(this.getName()+"当前队列为空");
                        try {
                            queue.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    queue.poll();
                    queue.notify();
                    System.out.println(this.getName()+"消费者消费一条任务,当前队列长度为" + queue.size());
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }
    public static void main(String[] args){
        pac p = new pac();
        Producer producer = p.new Producer();
        Producer producer1 = p.new Producer();
        Consumer consumer = p.new Consumer();
        Consumer consumer1 = p.new Consumer();
        producer.setName("s1");
        producer1.setName("s2");
        consumer.setName("c1");
        consumer1.setName("c2");
        producer.start();
        producer1.start();
        consumer.start();
        consumer1.start();
    }
}

举报

相关推荐

0 条评论