0
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());
    }
}
}

The problem is similar to producer consumer. Here producex will increase x by 1, and will increase again until x is printed by printx. But, seems no result. Where is the bug?

Gopal
  • 729
  • 2
  • 8
  • 19

1 Answers1

3

PrintX has no run() method. Nothing for it to do.

mah
  • 39,056
  • 9
  • 76
  • 93