实现生产者消费者问题中,在代码中的某个地方调用Thread.currentThread().notifyall()会报错,
而用this.notifyall()不会报错,代码:
public class Consumer extends Thread {
/* * 消费者线程 */
private Store store=null;
@Override
public void run() {
store=Store.getStore();
store.consumer();
}
}
public class Producer extends Thread {
private Store store=null;
/* *生产者线程 */
@Override
public void run() {
store=Store.getStore();
store.produce();
}
}
public 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(); }
}
}
请说明2者之间有什么差异,谢谢 |