Java线程生产者与消费者

来源:百度知道 编辑:UC知道 时间:2024/06/25 09:41:44
public class TextThread{
public static void main(String[] args){
Basket bk=new Basket();
Producer p=new Producer(bk);
Consumer c=new Consumer(bk);
new Thread(c).start();
new Thread(p).start();

}
}

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

class Basket{
static int index=0;
ManTou[] mArray=new ManTou[6];
public synchronized void add(ManTou m){
while(index==mArray.length){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
this.notify();
mArray[index]=m;
index++;

}
public synchronized ManTou del(){
while(index==0){
try{
this.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
}
thi

改成这样就可以了

class WoTou {
int id;
WoTou(int id) {
this.id=id;
}
public String toString() {
return "WoTou"+id;
}
}

class SynStack {
WoTou[] ss = new WoTou[6];
int index;
SynStack(int index) {
this.index=index;
}
public synchronized void push(WoTou wt) {
while(index==ss.length) {
try {
this.wait();
}catch (InterruptedException e) {
e.printStackTrace();
}

}
this.notify();
ss[index]=wt;
index++;

}
public synchronized WoTou pop() {
while(index==0) {
try {
this.wait();
}catch(InterruptedException e) {
e.printStackTrace();
}

}
this.notify();
index--;
return ss[index];

}
}

class