线程—代码模拟—生产者-消费者

尚学堂—马士兵-java系列网上免费视频教程

知识点:
1.Thread.sleep();
2.Runnable接口
3.Object.wait()
4.Object.notify();
5.if 和 While 的区别
6.synchronized 关键字

ProducerConsumer.java

1.其实,编译后会生成5个class文件。但只需运行 ProducerConsumer.class即可。
2.如果想在你的console中显示中文,请将.java文件的编码设为GB2312

[code]
/**
* 【生产者与消费者】
*
* 注意:
* 1、在使用wait()时,wait()最好写在while中。不要写在if else中。
* 2、wait()语句只能使用在synchronized语句中,用于使synchronize释放对其内部对象的锁定。
* 3、只要使用了wait(),在while外面一定要用notify();用于通知其它线程可以执行了。
*
*/

public class ProducerConsumer {
public static void main(String[] args){
SyncStack ss = new SyncStack();
Producer p = new Producer(ss);
Consumer c = new Consumer(ss);
new Thread(p).start();
new Thread(c).start();
}
}

class Wotou {
int id;
Wotou(int id){
this.id = id;
}
@Override
public String toString(){
return "Wotou: " + id;
}
}

class SyncStack{
int index = 0;
Wotou[] arrWt = new Wotou[6];

public synchronized void push(Wotou wt){
while(index == arrWt.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
arrWt[index] = wt;
index ++;
}
public synchronized Wotou pop(){
while(index == 0){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
index --;
return arrWt[index];

}
}

class Producer implements Runnable{
SyncStack ss = null;
Producer(SyncStack 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(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}

class Consumer implements Runnable{
SyncStack ss = null;
Consumer(SyncStack 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(500);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
[/code]


--
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值