一个很好的小例子来演示java中的wait()和notify()方法 [英] A good small example to demonstrate wait() and notify() method in java

查看:167
本文介绍了一个很好的小例子来演示java中的wait()和notify()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Can anybody please provide me a good small example demonstrate wait() and notify() functionality in java. I've tried with the below piece of code but it's not showing what i expected.

public class WaitDemo {
    int i = 10;

    int display() {
        System.out.println("Lexmark");
        i++;
        return i;
    }
}





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) {

            }

        }
    }
}

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

The issue is that the method in the class WaitDemo is not getting executed and as per my idea the SOP after wait() should execute. Please help me out on this.

推荐答案

你有两个级别的大括号​​ {尝试块中。如果你删除内部集合(似乎没有做任何事情),那是否可以解决问题?

You've got two levels of braces { in your try block. If you remove the inner set (which doesn't appear to do anything), does that fix the problem?

有几个例子,所有这些都证明了使用。最后一个链接是一组可以帮助您的结果。如果您需要更具体的内容,请告诉我您的应用尝试的内容,我可以尝试找到更适合您情况的示例。

There are several examples around, all of which demonstrate the use. The last link is a set of results that can help you out. If you need more specific things, let me know what it is that your app is trying to do, and I can try to find examples that are more specific to your situation.

  • http://www.javamex.com/tutorials/wait_notify_how_to.shtml
  • http://www.java-samples.com/showtutorial.php?tutorialid=306
  • http://www.coderanch.com/t/234235/threads/java/Wait-Example
  • https://www.google.com/search?q=wait%28%29+example+java&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a

这篇关于一个很好的小例子来演示java中的wait()和notify()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆