博客
关于我
生产者消费者 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 导入 sql 文件时 ERROR 1046 (3D000) no database selected 错误的解决
查看>>
mysql 导入导出大文件
查看>>
MySQL 导出数据
查看>>
mysql 将null转代为0
查看>>
mysql 常用
查看>>
MySQL 常用列类型
查看>>
mysql 常用命令
查看>>
Mysql 常见ALTER TABLE操作
查看>>
MySQL 常见的 9 种优化方法
查看>>
MySQL 常见的开放性问题
查看>>
Mysql 常见错误
查看>>
mysql 常见问题
查看>>
MYSQL 幻读(Phantom Problem)不可重复读
查看>>
mysql 往字段后面加字符串
查看>>
mysql 快照读 幻读_innodb当前读 与 快照读 and rr级别是否真正避免了幻读
查看>>
MySQL 快速创建千万级测试数据
查看>>
mysql 快速自增假数据, 新增假数据,mysql自增假数据
查看>>
MySql 手动执行主从备份
查看>>
Mysql 批量修改四种方式效率对比(一)
查看>>
Mysql 报错 Field 'id' doesn't have a default value
查看>>