本文共 1839 字,大约阅读时间需要 6 分钟。
package com.test;/** * 生产者-消费者,使用java代码实现效果 * 定义:生产者(Producer)生产商品给仓库(Warehouse),消费者(Consumer)消费商品,仓库最多放20个商品 * 1、存在共享数据,商品的数量(线程同步) * 2、生产者和消费者之前的通信(线程通信) * @author CCQ * */public class ProducerAndConsumer { public static void main(String[] args) { Warehouse warehouse = new Warehouse(); Producer p1 = new Producer(warehouse); Consumer c1 = new Consumer(warehouse); Thread pt1 = new Thread(p1); pt1.setName("生产者1"); Thread pt2 = new Thread(p1); pt2.setName("生产者2"); Thread ct1 = new Thread(c1); ct1.setName("消费者1"); pt1.start(); pt2.start(); ct1.start(); }}// 生产者class Producer implements Runnable{ Warehouse warehouse; public Producer(Warehouse warehouse) { this.warehouse = warehouse; } @Override public void run() { // 生产者在不停的生产商品 while(true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } warehouse.add(); } }}// 消费者class Consumer implements Runnable{ Warehouse warehouse; public Consumer(Warehouse warehouse) { this.warehouse = warehouse; } @Override public void run() { // 消费者在不同消费商品 while(true) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } warehouse.reduce(); } }}// 仓库class Warehouse{ private int product; // 添加商品方法 原子操作 P public synchronized void add() { if(product >= 20) { try { wait();//释放cpu资源,进入等待状态 } catch (InterruptedException e) { e.printStackTrace(); } }else { product++; System.out.println(Thread.currentThread().getName()+ "生产了第" + product + "个商品"); notifyAll();//唤醒所有的等待的线程 } } // 减少商品方法 原子操作 V public synchronized void reduce(){ if(product <= 0) { try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } }else { System.out.println(Thread.currentThread().getName()+ "消费了第" + product + "个商品"); product--; notifyAll(); } }}
转载地址:http://mgzin.baihongyu.com/