您的位置:首页 > 其它

线程 --生产和消费问题

2011-08-09 15:35 295 查看
package com.lan;

/**

* 生产和消费的问题

* @ClassName: ProducerConsumer

* @Description: TODO

* @author LanHantong

* @date 2011-8-9 下午03:13:39

*

*/

public class ProducerConsumer {

/**

* @param args

*/

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;
}

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;

//构造方法 持有SyncStack的引用

Producer(SyncStack ss){

this.ss = ss;

}

@Override

public void run() {

// TODO Auto-generated method stub

for(int i=0; i<20; i++){

WoTou wt = new WoTou(i);

ss.push(wt);

System.out.println("生产了,"+wt);

try {

Thread.sleep((int)(Math.random()*200));

} catch (InterruptedException e) {

e.printStackTrace();

}

}
}

}

//消费线程

class Consumer implements Runnable{

SyncStack ss = null;

//构造方法 持有SyncStack的引用

Consumer(SyncStack ss){

this.ss = ss;

}

@Override

public void run() {

// TODO Auto-generated method stub

for(int i=0; i<20; i++){

WoTou wt = ss.pop();

System.out.println("消费了,"+wt);

try {

Thread.sleep((int)(Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: