简体   繁体   English

用Java通知并等待

[英]Notify and Wait in Java

i have a problem with notify() and wait(). 我有一个notify()和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. 我无法访问我的NOTIFY方法。

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

    }   
}

synchronize your NOTIFY method. 同步您的NOTIFY方法。 Also use watek.NOTIFY() instead of TH.NOTIFY(). 还要使用watek.NOTIFY()代替TH.NOTIFY()。

You simply have a race. 你只是一场比赛。 The call to NOTIFY in the main method might happen before the wait in the new thread. main方法中对NOTIFY的调用可能在新线程中的wait之前进行。 There would then be nothing left to wake it up. 这样一来,便没有什么可以唤醒它了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM