//帮我看看下面出错的原因
class Consumer extends Thread {
private Store store=null;
public void run() {
store=Store.getStore();
store.consumer();
}
}
class Producer extends Thread {
private Store store=null;
public void run() {
store=Store.getStore();
store.produce();
}
}
class Store {
private int length=0;
private int size=10;
private static Store s=null;
public Store(){}
public Store(int len,int size){
this.length=len;
this.size=size;
}
static {
s=new Store();
}
public static Store getStore(){
if(s!=null){
return s;
}
return new Store();
}
//生产者方法
public synchronized void produce(){
while(length==size){
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//此处用Thread.currentThred.notifyAll()会报错
this.notifyAll();
System.out.println(Thread.currentThread().getName());
length=length+1;
System.out.println(Thread.currentThread().getName()+"生产一件产品,当前数量为:"+length);
}
//消费者方法
public synchronized void consumer(){
while(length==0){
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//通知生产者线程
//此处用Thread.currentThread().notifyAll()会报错
this.notifyAll();
length=length-1;
System.out.println(Thread.currentThread().getName()+"消费一件产品,剩余数量为:"+length);
}
}
public class MainClass {
static Consumer con=null;
static Producer pro=null;
public static void main(String[] args) {
for(int i=0;i<10;i++){
con=new Consumer();
con.start();
}
for(int i=0;i<10;i++){
pro=new Producer();
pro.start();
}
}
}
|