user3402584
user3402584

Reputation: 410

Notify and Wait in Java

i have a problem with notify() and wait(). I want my main thread to be able to force other thread to wait and notify whenever i want to. It seems i dont understand everything because notify doesnt work. I cant acces my NOTIFY method.

Here is my code:

MAIN THREAD:

public class troll {

    static Runnable R0;
    static Thread TH;

    public static void main(String[] args) {

        System.out.println("TROLOLOLL0");
        watek R0 = new watek();
        Thread TH = new Thread(R0);

        synchronized(TH){
            TH.start();
            R0.NOTIFY();
            }

    }

}

My THREAD Class:

public class watek implements Runnable {

    public watek(){

    }

    public  void run() {


        System.out.print("STOP");
            this.WAIT();
            System.out.print("Running again");

    }


    public synchronized void WAIT(){
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }   

    public  void NOTIFY(){
        notify();

    }   
}

Upvotes: 0

Views: 101

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

You simply have a race. The call to NOTIFY in the main method might happen before the wait in the new thread. There would then be nothing left to wake it up.

Upvotes: 1

SMA
SMA

Reputation: 37103

synchronize your NOTIFY method. Also use watek.NOTIFY() instead of TH.NOTIFY().

Upvotes: 1

Related Questions