博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者—消费者模式示例
阅读量:7120 次
发布时间:2019-06-28

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

package producerAndCustomer;import java.util.ArrayList;import java.util.List;public class Plate {    private List apples = new ArrayList();    public synchronized void putApple(Object apple){        if(apples.size()>0){            try {                wait();            } catch (InterruptedException e) {                // TODO: handle exception                e.printStackTrace();            }        }        apples.add(apple);        notify();        System.out.println("放了一个苹果");    }    public synchronized void getApple(){        if(apples.size()==0){            try {                wait();            } catch (InterruptedException e) {                // TODO: handle exception                e.printStackTrace();            }        }        Object apple = apples.get(0);        apples.clear();        notify();        System.out.println("get了一个红苹果");            }    }
package producerAndCustomer;public class Add implements Runnable {    private Plate applePlate;    private Object apple = new Object();    public Add(Plate applePlate){        this.applePlate = applePlate;    }    @Override    public void run() {        // TODO Auto-generated method stub        for(int i = 0 ;i<5;i++){            applePlate.putApple(apple);        }    }}
package producerAndCustomer;public class Get implements Runnable {    private Plate applePlate;    public Get(Plate applePlate){        this.applePlate = applePlate;    }    @Override    public void run() {        // TODO Auto-generated method stub        for(int i=0;i<5;i++){            applePlate.getApple();        }    }}
package producerAndCustomer;public class SynchroTest {	public static void main(String args[]){		Plate myPlate = new Plate();		new Thread(new Get(myPlate)).start();		new Thread(new Add(myPlate)).start();	}}

  

转载于:https://www.cnblogs.com/Keven02/p/7410381.html

你可能感兴趣的文章
java写一个爬虫
查看>>
Drill官网文档翻译六:存储插件的注册
查看>>
poj 1502 单源最短路径
查看>>
CUDNN v3特性
查看>>
为什么C# md5 32位加密算法,密码明文会出现31位
查看>>
怎么通过java去调用并执行shell脚本以及问题总结
查看>>
Android桌面悬浮窗效果实现,仿360手机卫士悬浮窗效果
查看>>
mysql分析函数的实现
查看>>
Android应用程序插件化研究之DexClassLoader
查看>>
如何站在双11的肩膀上 详解阿里云企业级互联网架构
查看>>
记一次Spring Batch完整入门实践
查看>>
小程序登录及用户信息和手机号的获取
查看>>
[Vue] Computed property "XXX" was assigned to but it has no setter.
查看>>
设计模式系列之「装饰模式」
查看>>
OSI 七层网络协议的定义与理解
查看>>
Less(v3.9.0)使用详解—变量
查看>>
Javascript对象
查看>>
Spring Boot快速注册服务脚本
查看>>
JavaScript嵌套函数this的指向问题
查看>>
Spring Cloud教程 (二)应用程序上下文服务层次结构
查看>>