博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生产者和消费者问题,但还是对其中的notify()方法不明白
阅读量:6894 次
发布时间:2019-06-27

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

hot3.png

public class ProducerConsumer {public static void main (String []args){	SycStack ss=new SycStack();	Producer p=new Producer(ss);	Consumer c=new Consumer(ss);	new Thread(p).start();	new Thread(c).start();}}class Wotou{	int id=0;	public Wotou(int id){		this.id=id;	}	public String toString (){		return "Wotou :"+id;	}}class SycStack{	int index=0;	Wotou [] arrWotou=new Wotou[6];	public synchronized void push(Wotou wt){		while(index==arrWotou.length){			try{this.wait();			}catch(InterruptedException e){				e.printStackTrace();			}			}this.notify();		arrWotou[index]=wt;		index++;	}	public synchronized Wotou pop(){		while(index==0){			try {				this.wait();			}catch(InterruptedException e){				e.printStackTrace();			}		}this.notify();		index--;		return arrWotou[index];			}}class Producer implements Runnable{	SycStack ss=null;	Producer (SycStack ss){		this.ss=ss;			}	public void run(){		for(int i=0;i<20;i++){			Wotou wt =new Wotou(i);			ss.push(wt);			System.out.println("生产了:"+wt);			try{			Thread.sleep(1000);			}catch(InterruptedException e){				e.printStackTrace();			}		}	}}class Consumer implements Runnable{	SycStack ss=null;Consumer (SycStack ss){		this.ss=ss;			}	public void run(){		for(int i=0;i<20;i++){			Wotou wt =ss.pop();				System.out.println("消费了:"+wt);	try{		Thread.sleep(1000);		}catch(InterruptedException e){			e.printStackTrace();		}					}	}}

转载于:https://my.oschina.net/yanjianhai/blog/60681

你可能感兴趣的文章
redis-sentinel 做HA
查看>>
图为先C++笔试20131017
查看>>
模仿墨迹天气-demo
查看>>
mysql基于日志点的复制步骤
查看>>
查看centos中的用户和用户组
查看>>
Elixir ABC 1
查看>>
ZeroSpeech
查看>>
Fiddler 调试手机应用
查看>>
常用的正则表达式
查看>>
Jstl 中<c:if test="${value=='0'}"> 不能做判断??
查看>>
python matplotlib及sklearn安装
查看>>
困惑2017?
查看>>
KOTree
查看>>
BlockAlertsAnd-ActionSheets
查看>>
开源 java CMS - FreeCMS2.5 标签formTable自定义表单
查看>>
FreeCMS视频教程 将FreeCMS导入myeclipse
查看>>
Android 8.0 SystemUI(一):图文并茂的介绍 :D
查看>>
1wifi 简介(框架)
查看>>
internet && intranet
查看>>
go get报错 error: RPC failed; result=56, HTTP code =
查看>>