java 多种方式实现生产者消费者模式

本文介绍了使用wait()和notify()方法、阻塞队列(BlockingQueue)以及Lock和Condition三种方式在Java中实现生产者消费者模式。通过示例代码详细展示了每种方法的实现过程。

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

1. 使用wait()和notify()方法:

import java.util.LinkedList;

class ProducerConsumer {
    private LinkedList<byte[]> buffer = new LinkedList<>();
    private int capacity = 10;

    public void produce() throws InterruptedException {
        while (true) {
            synchronized (this) {
                while (buffer.size() == capacity) {
                    wait();
                }
                byte[] data = generateData();
                buffer.add(data);
                System.out.println("Produced: " + data.length + " bytes");
                notify();
                Thread.sleep(1000);
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            synchronized (this) {
                while (buffer.isEmpty()) {
                    wait();
                }
                byte[] data = buffer.removeFirst();
                System.out.println("Consumed: " + data.length + " bytes");
                notify();
                Thread.sleep(1000);
            }
        }
    }

    private byte[] generateData() {
        // 生成byte数组数据的逻辑
        return new byte[10];
    }
}

public class Main {
    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producerThread = new Thread(() -> {
            try {
                pc.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumerThread = new Thread(() -> {
            try {
                pc.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}

2. 使用阻塞队列(BlockingQueue):

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class ProducerConsumer {
    private BlockingQueue<byte[]> buffer = new ArrayBlockingQueue<>(10);

    public void produce() throws InterruptedException {
        while (true) {
            byte[] data = generateData();
            buffer.put(data);
            System.out.println("Produced: " + data.length + " bytes");
            Thread.sleep(1000);
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            byte[] data = buffer.take();
            System.out.println("Consumed: " + data.length + " bytes");
            Thread.sleep(1000);
        }
    }

    private byte[] generateData() {
        // 生成byte数组数据的逻辑
        return new byte[10];
    }
}

public class Main {
    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producerThread = new Thread(() -> {
            try {
                pc.produce();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread consumerThread = new Thread(() -> {
            try {
                pc.consume();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        producerThread.start();
        consumerThread.start();
    }
}

3. 使用Lock和Condition:

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

class ProducerConsumer {
    private LinkedList<byte[]> buffer = new LinkedList<>();
    private int capacity = 10;
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public void produce() throws InterruptedException {
        while (true) {
            lock.lock();
            try {
                while (buffer.size() == capacity) {
                    notFull.await();
                }
                byte[] data = generateData();
                buffer.add(data);
                System.out.println("Produced: " + data.length + " bytes");
                notEmpty.signal();
                Thread.sleep(1000);
            } finally {
                lock.unlock();
            }
        }
    }

    public void consume() throws InterruptedException {
        while (true) {
            lock.lock();
            try {
                while (buffer.isEmpty()) {
                    notEmpty.await();
                }
                byte[] data = buffer.removeFirst();
                System.out.println("Consumed: " + data.length + " bytes");
                notFull.signal();
                Thread.sleep(1000);
            } finally {
                lock.unlock();
            }
        }
    }

    private byte[] generateData() {
        // 生成byte数组数据的逻辑
        return new byte[10];
    }
}

public class Main {
    public static void main(String[] args) {
        ProducerConsumer pc = new ProducerConsumer();

        Thread producerThread = new Thread(()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值