生产者消费者模式代码java

生产者消费者模式是多线程编程中的一种常见模式,用于解决生产者和消费者之间的协作问题。在Java中,可以使用多线程和共享队列来实现生产者消费者模式。

java
import java.util.LinkedList; import java.util.Queue; class ProducerConsumer { private Queue<Integer> buffer = new LinkedList<>(); private int capacity = 5; public void produce() throws InterruptedException { int item = 0; while (true) { synchronized (this) { while (buffer.size() == capacity) { wait(); } System.out.println("Producer produced: " + item); buffer.add(item++); notify(); Thread.sleep(1000); // 模拟生产过程 } } } public void consume() throws InterruptedException { while (true) { synchronized (this) { while (buffer.isEmpty()) { wait(); } int item = buffer.poll(); System.out.println("Consumer consumed: " + item); notify(); Thread.sleep(1000); // 模拟消费过程 } } } } 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(); } }

这个示例中,我们创建了一个名为ProducerConsumer的类,其中包含一个共享队列buffer,并定义了生产者和消费者的produceconsume方法。生产者不断向队列中添加元素,如果队列已满,则等待,而消费者不断从队列中取出元素,如果队列为空,则等待。通过synchronized关键字和waitnotify方法来确保线程安全和协作。生产者和消费者线程在main方法中启动并运行。

java
import java.util.LinkedList; import java.util.Queue; class ProducerConsumer { private Queue<Integer> buffer = new LinkedList<>(); private int capacity = 5; private boolean isTerminated = false; public void produce() throws InterruptedException { int item = 0; while (!isTerminated) { synchronized (this) { while (buffer.size() == capacity) { wait(); } if (isTerminated) { break; } System.out.println("Producer produced: " + item); buffer.add(item++); notify(); Thread.sleep(1000); // 模拟生产过程 } } } public void consume() throws InterruptedException { while (!isTerminated || !buffer.isEmpty()) { synchronized (this) { while (buffer.isEmpty() && !isTerminated) { wait(); } if (isTerminated && buffer.isEmpty()) { break; } int item = buffer.poll(); System.out.println("Consumer consumed: " + item); notify(); Thread.sleep(1000); // 模拟消费过程 } } } public void stop() { isTerminated = true; } } 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(); // 模拟运行一段时间后终止生产者和消费者 try { Thread.sleep(5000); pc.stop(); } catch (InterruptedException e) { e.printStackTrace(); } } }

在上述代码中,我们添加了一个isTerminated标志,以便生产者和消费者线程可以在满足终止条件时退出循环。在stop方法中设置此标志,然后在main方法中等待一段时间后调用它来终止线程。

这个示例还包含了更多的异常处理和日志输出,以帮助您更好地理解线程的行为。您可以根据实际需求进行进一步的自定义和扩展。

标签