本文共 2989 字,大约阅读时间需要 9 分钟。
以下是一个使用Java多线程实现的生产者-消费者模型示例,该模型展示了如何在多线程环境中使用wait和notify方法来实现线程同步。
import java.util.LinkedList;import java.util.Queue;import java.util.Random;public class NotifyWaitTest { public static void main(String[] args) { Queuequeue = new LinkedList<>(); Producer p = new Producer(queue); Consumer c = new Consumer(queue); p.produce(); c.consume(); }}
public class Producer { private final Queuequeue; private static final Random r = new Random(50); public Producer(Queue queue) { this.queue = queue; } public void produce() { Thread pt = new Thread(new Runnable() { @Override public void run() { int count = 100; synchronized (queue) { while (count > 0) { int i = r.nextInt(); queue.add(i); queue.notify(); count--; } } } }); pt.start(); }}
public class Consumer { private final Queuequeue; public Consumer(Queue queue) { this.queue = queue; } public void consume() { Thread cm = new Thread(new Runnable() { @Override public void run() { int count = 100; synchronized (queue) { try { while (count > 0) { if (queue.isEmpty()) { queue.wait(); } int i = queue.poll(); System.out.println("Consume " + i); count--; } } catch (InterruptedException ie) { System.out.println(ie.getMessage()); } } } }); cm.start(); }}
生产者(Producer)类:
produce()
方法中,创建一个新的线程,运行一个Runnable任务。count
循环从100递减到0。queue.notify()
,通知等待的消费者线程。消费者(Consumer)类:
consume()
方法中,创建一个新的线程,运行一个Runnable任务。count
循环从100递减到0。queue.poll()
,取出队列中的整数并打印出来。queue.wait()
,等待直到有数据被生产并通知。主方法(main):
LinkedList
作为Queue。Producer
实例,并传递Queue。Consumer
实例,并传递相同的Queue。produce()
和consume()
方法,分别启动生产者和消费者线程。Queue
和synchronized
关键字确保了线程安全,避免了数据竞争和加速。queue.notify()
,唤醒等待的消费者线程。queue.wait()
,直到有数据被生产并通知。Random
生成随机数,确保每次生成的数据是随机的。queue.poll()
方法中取出队列中的整数并打印出来,直到所有数据被消费完毕。这种设计模式在多线程环境中非常有用,可以应用于资源有限的环境中,确保生产者和消费者能够高效地交换数据。
转载地址:http://finbz.baihongyu.com/