一个很好的小例子来演示java中的wait()和notify()方法

Sou*_*Bag 8 java multithreading notify wait

任何人都可以在java中为我提供一个很好的小例子演示wait()和notify()功能.我试过下面的代码,但它没有显示我的预期.

public class WaitDemo {
    int i = 10;

    int display() {
        System.out.println("Lexmark");
        i++;
        return i;
    }
}
Run Code Online (Sandbox Code Playgroud)
public class ClassDemo1 extends Thread {

    private WaitDemo wd = new WaitDemo();

    public static void main(String[] args) {
        ClassDemo1 cd1 = new ClassDemo1();
        ClassDemo1 cd2 = new ClassDemo1();
        cd1.setName("Europe");
        cd2.setName("America");
        cd1.start();
        cd2.start();

    }

    synchronized void display() {
        System.out.println("Hello");
        notifyAll();
    }

    public void run() {

        synchronized (this) {
            try {
                {
                    notify();
                    System.out.println("The thread is " + currentThread().getName());
                    wait();
                    System.out.println("The value is " + wd.display());
                }
            } catch (InterruptedException e) {

            }

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是WaitDemo类中的方法没有被执行,根据我的想法,wait()之后的SOP应该执行.请帮我解决这个问题.

jef*_*unt 3

{您的块中有两层大括号try。如果删除内部集(它似乎没有执行任何操作),是否可以解决问题?

周围有几个示例,所有这些示例都演示了其用法。最后一个链接是一组可以帮助您的结果。如果您需要更具体的事情,请让我知道您的应用程序正在尝试做什么,我可以尝试找到更适合您情况的示例。