【Java多线程二】多路条件解决生产者消费者问题

本文展示了一个使用Java实现的线程间通信的例子。通过一个共享的Plate类,多个生产者线程和消费者线程能够协调工作,确保数据在并发环境下的正确同步。该示例利用了ReentrantLock和Condition来实现线程间的等待和唤醒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.tom;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Plate<T> {
    private final Lock lock = new ReentrantLock();
    private final Condition PLATE_NOT_FULL = lock.newCondition();
    private final Condition PLATE_NOT_EMPTY = lock.newCondition();

    private final Queue<T> plates = new LinkedList<T>();
    private int size;

    public Plate(int size) {
        this.size = size;
    }

    public void produce(T fruit) {
        lock.lock();
        try {
            if (plates.size() >= size) {
                try {
                    System.out.println(Thread.currentThread().getName() + ", The plate is full..waiting to put into the plate");
                    PLATE_NOT_FULL.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println(Thread.currentThread().getName() + ", The plate is not full..put the fruit  into the plate: " + fruit);
            plates.offer(fruit);
            PLATE_NOT_EMPTY.signalAll();
        } finally {
            if (lock != null){
                lock.unlock();
            }
        }

    }

    public T consume() {
        T fruit = null;
        lock.lock();
        try {
            if (plates.isEmpty()) {
                try {
                    System.out.println(Thread.currentThread().getName() + ", The plate is empty..waiting to consume");
                    PLATE_NOT_EMPTY.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            fruit = plates.poll();
            System.out.println(Thread.currentThread().getName() + ",The plate is not empty, consume the fruit: " + fruit);
            PLATE_NOT_FULL.signalAll();
        } finally {
            if (lock != null){
                lock.unlock();
            }
        }

        return fruit;
    }

}

public class ThreadCommunication {

    private static volatile boolean shutdown = false;

    public static void main(String[] args) {

        final Plate<Integer> plate = new Plate<Integer>(8);

        Thread[] consumers = new Thread[3];

        for (int i = 0; i < consumers.length; i++) {

            consumers[i] = new Thread() {
                @Override
                public void run() {

                    while (!shutdown) {
                        plate.consume();
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            };
            consumers[i].start();
        }


        Thread[] producers = new Thread[2];

        for (int i = 0; i < producers.length; i++) {
            producers[i] = new Thread() {
                @Override
                public void run() {
                    while (!shutdown) {
                        plate.produce(ThreadLocalRandom.current().nextInt(100, 1000));
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            producers[i].start();
        }

        try {
            Thread.sleep(6000);
            shutdown = true;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值