博客
关于我
生产者消费者 Java
阅读量:193 次
发布时间:2019-02-28

本文共 5430 字,大约阅读时间需要 18 分钟。

synchronized实现

public class App {       private int num;    /**     * 生产     */    public void product() {           try {               // 生产耗时            Thread.sleep(1000);            synchronized (this) {                   while (num >= 100) {                       wait();                }                num++;                System.out.println("生产");                System.out.println("库存量:" + num);                notifyAll();            }        } catch (InterruptedException e) {               e.printStackTrace();        }    }    /**     * 消费     */    public void sell() {           try {               // 卖出耗时            Thread.sleep(500);            synchronized (this) {                   while (num <= 0) {                       wait();                }                num--;                System.out.println("卖出");                System.out.println("库存量:" + num);                notifyAll();            }        } catch (InterruptedException e) {               e.printStackTrace();        }    }    public static void main(String[] args) throws Exception {           App app = new App();        Runnable product = new Runnable() {               @Override            public void run() {                   while (true) {                       app.product();                }            }        };        Runnable sell = new Runnable() {               @Override            public void run() {                   while (true) {                       app.sell();                }            }        };        for (int i = 0; i < 5; i++) {               System.out.println("投产");            new Thread(product).start();        }        for (int i = 0; i < 10; i++) {               System.out.println("销售");            new Thread(sell).start();        }    }}

阻塞队列实现

import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.BlockingQueue;import java.util.concurrent.atomic.AtomicInteger;public class App {       private BlockingQueue
blockingQueue=new ArrayBlockingQueue<>(100); private AtomicInteger atomicInteger=new AtomicInteger(); /** * 生产 */ public void product() { try { // 生产耗时 Thread.sleep(1000); blockingQueue.offer(atomicInteger.incrementAndGet()); System.out.println("工厂"+Thread.currentThread().getName()+"生产\n库存量:" + blockingQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 消费 */ public void sell() { try { // 卖出耗时 Thread.sleep(500); System.out.println("消费者"+Thread.currentThread().getName()+"购买"+blockingQueue.take()+"号商品\n库存量:" + blockingQueue.size()); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws Exception { App app = new App(); Runnable product = new Runnable() { @Override public void run() { while (true) { app.product(); } } }; Runnable sell = new Runnable() { @Override public void run() { while (true) { app.sell(); } } }; for (int i = 0; i < 3; i++) { System.out.println("投产"); new Thread(product).start(); } for (int i = 0; i < 5; i++) { System.out.println("销售"); new Thread(sell).start(); } }}

ReentrantLock实现

import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.ReentrantLock;public class App {       private ReentrantLock lock = new ReentrantLock();    private final Condition notFull = lock.newCondition();    private final Condition notEmpty = lock.newCondition();    private int num = 0;    public void product() {           try {               Thread.sleep(1000);            lock.lock();            while (num > 100) {                   notFull.await();            }            num++;            System.out.println("工厂" + Thread.currentThread().getName() + "生产\n库存:" + num);            notEmpty.signalAll();        } catch (Exception e) {               e.printStackTrace();        } finally {               lock.unlock();        }    }    public void sell() {           try {               Thread.sleep(800);            lock.lock();            while (num <= 0) {                   notEmpty.await();            }            num--;            System.out.println("顾客" + Thread.currentThread().getName() + "购买\n库存:" + num);            notFull.signalAll();        } catch (Exception e) {               e.printStackTrace();        } finally {               lock.unlock();        }    }    public static void main(String[] args) {           App app = new App();        for (int i = 0; i < 10; i++) {               new Thread(new Runnable() {                   @Override                public void run() {                       while (true) {                           app.product();                    }                }            }).start();        }        for (int i = 0; i < 5; i++) {               new Thread(new Runnable() {                   @Override                public void run() {                       while (true) {                           app.sell();                    }                }            }).start();        }    }}

转载地址:http://upvj.baihongyu.com/

你可能感兴趣的文章
MySQL 到底能不能放到 Docker 里跑?
查看>>
mysql 前缀索引 命令_11 | Mysql怎么给字符串字段加索引?
查看>>
MySQL 加锁处理分析
查看>>
mysql 协议的退出命令包及解析
查看>>
mysql 参数 innodb_flush_log_at_trx_commit
查看>>
mysql 取表中分组之后最新一条数据 分组最新数据 分组取最新数据 分组数据 获取每个分类的最新数据
查看>>
MySQL 命令和内置函数
查看>>
mysql 四种存储引擎
查看>>
MySQL 在并发场景下的问题及解决思路
查看>>
MySQL 基础架构
查看>>
MySQL 基础模块的面试题总结
查看>>
MySQL 备份 Xtrabackup
查看>>
mYSQL 外键约束
查看>>
mysql 多个表关联查询查询时间长的问题
查看>>
mySQL 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>