【JAVA】 实现消费者生产者

通过wait()和 notifyAll()实现

public class PublicQueue {

    public int putindex = 0;
    public int maxcount = 10;

    public synchronized void add(){

        while(putindex >= maxcount){
            try {
                System.out.println("没有东西可以加了");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        notifyAll();
        putindex++;
        System.out.println(Thread.currentThread().getName() + " 生产加1变成:"+putindex);

    }

    public synchronized void remove(){
        while(putindex == 0) {
            try {
                System.out.println("没有东西可以减了");
                wait();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        notifyAll();
        putindex--;
        System.out.println(Thread.currentThread().getName()+" 消费减1:"+putindex );

    }

}
public class Consumer implements Runnable {
    private PublicQueue publicQueue;

    public Consumer(PublicQueue publicQueue){
        this.publicQueue = publicQueue;
    }


    @Override
    public  void run(){
        while (true){
            try {
                Thread.sleep(3000);
                publicQueue.remove();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}

public class Producer implements Runnable {

    private PublicQueue publicQueue;

    public Producer(PublicQueue publicQueue){
        this.publicQueue = publicQueue;
    }


    @Override
    public  void run(){
        while (true){
            try {
                Thread.sleep(1000);
                publicQueue.add();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }


}
    public static void main(String[] args) {
        PublicQueue publicQueue = new PublicQueue();
        Thread p1 = new Thread(new Producer(publicQueue), "produce1");
        Thread p2 = new Thread(new Producer(publicQueue), "produce2");
        Thread p3 = new Thread(new Producer(publicQueue), "produce3");
        Thread s1 = new Thread(new Consumer(publicQueue), "consumer1");
        Thread s2 = new Thread(new Consumer(publicQueue), "consumer2");
        Thread s3 = new Thread(new Consumer(publicQueue), "consumer3");
        p1.start();
        p2.start();
        p3.start();
        s1.start();
        s2.start();
        s3.start();
    }

BlockingQueue 实现

public class BlockingQueueTest {

    public static  int count = 0;
    public BlockingQueue blockingQueue = new ArrayBlockingQueue(10);


    public static void main(String[] args) {
        BlockingQueueTest test3 = new BlockingQueueTest();
        new Thread(test3.new ProducerTest()).start();
        new Thread(test3.new ConsumerTest()).start();
        new Thread(test3.new ProducerTest()).start();
        new Thread(test3.new ConsumerTest()).start();
        new Thread(test3.new ProducerTest()).start();
        new Thread(test3.new ConsumerTest()).start();
        new Thread(test3.new ProducerTest()).start();
        new Thread(test3.new ConsumerTest()).start();
    }


    class ProducerTest implements  Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    blockingQueue.put(1);//add会抛出异常 put会阻塞
                    count++;
                    System.out.println(Thread.currentThread().getName()
                            + "生产者生产,目前总共有" + count);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }
    }
    class ConsumerTest implements  Runnable{

        @Override
        public void run() {
            while (true){
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                try {
                    blockingQueue.take();
                    count--;
                    System.out.println(Thread.currentThread().getName()
                            + "消费者消费,目前总共有" + count);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }



            }
        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中,我们可以使用多线程和共享队列来实现消费者生产者问题。以下是一个简单的示例代码: ``` import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { private Queue<Integer> queue = new LinkedList<>(); private final int MAX_SIZE = 10; public void start() { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); } private class Producer implements Runnable { public void run() { while (true) { synchronized (queue) { while (queue.size() == MAX_SIZE) { try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int data = (int) (Math.random() * 100); queue.offer(data); System.out.println("Producer produce " + data); queue.notifyAll(); } } } } private class Consumer implements Runnable { public void run() { while (true) { synchronized (queue) { while (queue.isEmpty()) { try { queue.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } int data = queue.poll(); System.out.println("Consumer consume " + data); queue.notifyAll(); } } } } public static void main(String[] args) { ProducerConsumer pc = new ProducerConsumer(); pc.start(); } } ``` 在这个示例中,我们使用了一个LinkedList作为共享队列,生产者线程不断地往队列中添加数据,如果队列已满,则等待。消费者线程不断地从队列中取出数据,如果队列为空,则等待。每次生产者添加数据或消费者取出数据时,都需要发送notifyAll()方法的信号,以唤醒等待在队列上的线程。由于生产者消费者线程都会访问到共享队列,因此需要使用synchronized关键字来实现线程的同步和互斥。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值