生产者消费者问题

时间:2011-05-30 01:20:31

标签: java

public class Main {
public static void main(String[] args){
    XClass x = new XClass();
    ProduceX prodx = new ProduceX(x);
    PrintX printx = new PrintX(x);

    prodx.start();
    printx.start();
}
}
class XClass {
private int x;
private boolean produced = false;

public XClass(){
    this.x = 0;
}
public synchronized int modifyX(){
    while(produced==true){
        try{
            wait();
        }
        catch(InterruptedException ie){}
    }
    x=x+1;
    produced = true;
    notifyAll();
    return x;

}
public synchronized void printX(){
    while(produced==false){
        try{
            wait();
        }
        catch(InterruptedException ie){}
    }
    produced = false;
    System.out.println(Thread.currentThread().getName()+" prints "+x);
    notifyAll();
}

}
class PrintX extends Thread{
private XClass x;
public PrintX(XClass x){
    this.x = x;
}
public void printX(){
    for(int i=0;i<10;i++){
        x.printX();
    }
}
}
class ProduceX extends Thread{
private XClass x;
public ProduceX(XClass x){
    this.x = x;
}
public void run(){
    for(int i=0;i<10;i++){
        x.modifyX();
        System.out.println(Thread.currentThread().getName()+" increases x   to "+ x.modifyX());
    }
}
}

问题类似于生产者消费者。这里,producex会将x增加1,并且会再次增加,直到x由printx打印。但是,似乎没有结果。错误在哪里?

1 个答案:

答案 0 :(得分:3)

PrintX没有run()方法。没什么可做的。