博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者和消费者
阅读量:4180 次
发布时间:2019-05-26

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

用到 wait()、notify()/notifyAll()方法

public class Test15 {
/** * @param args */ public static void main(String[] args) { AppleBox ab=new AppleBox(); Producer p=new Producer(ab); Consumer c=new Consumer(ab); Consumer cd=new Consumer(ab); new Thread(p).start(); new Thread(c).start(); new Thread(cd).start(); }}//消息的对象=>消息class Apple{
int id; Apple(int id){ this.id=id; } public String toString(){ return "apple" +id; }}//容器class AppleBox{
int index=0; Apple[] apples=new Apple[5]; public synchronized void deposite(Apple apple){ while(index==apples.length){ try { this.wait(); //wait是Object 对象的方法 =>将这个对象所在的线程阻塞住 释放对象锁 } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll();//notifyAll也是Object对象的方法 =>通知其他线程启动 apples[index]=apple; index++; } public synchronized Apple withdraw(){ while(index==0){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.notifyAll(); index--; return apples[index]; }}class Producer implements Runnable{
AppleBox ab=null; Producer(AppleBox ab) { this.ab=ab; } @Override public void run() { for(int i=0;i<20;i++){ Apple a=new Apple(i); ab.deposite(new Apple(i)); System.out.println(Thread.currentThread().getName()+"生产了"+a); try { Thread.sleep((int)(Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}class Consumer implements Runnable{
AppleBox ab=null; public Consumer(AppleBox ab) { this.ab=ab; } @Override public void run() { for(int i=0;i<20;i++){ Apple a=ab.withdraw(); System.out.println(Thread.currentThread().getName()+"消费了"+a); try { Thread.sleep((int)(Math.random()*1000)); } catch (InterruptedException e) { e.printStackTrace(); } } }}

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

你可能感兴趣的文章
Hibernate中的数据的获取策略(fetching)
查看>>
Hibernate中通过HQL/JPQL查询的方式实现动态数据获取
查看>>
Hibernate中通过FetchProfile的方式实现动态数据获取
查看>>
Hibernate应用中通过JPA配置Entity缓存
查看>>
Hibernate中配置二级缓存的并发策略
查看>>
Hibernate中的Query cache(查询缓存)
查看>>
Hibernate的interceptors与events
查看>>
Android常用代码
查看>>
Cardboard虚拟现实开发初步(二)
查看>>
60个优秀的免费3D模型下载网站
查看>>
Cardboard虚拟现实开发初步(三)
查看>>
Android native和h5混合开发几种常见的hybrid通信方式
查看>>
Vista/Win7 UAC兼容程序开发指南
查看>>
IOS程序开发框架
查看>>
安装jdk的步骤
查看>>
简述JAVA运算符
查看>>
简易ATM源代码及运行结果
查看>>
简述Java中的简单循环
查看>>
用JAVA实现各种乘法表
查看>>
for双重循环实现图形
查看>>