【问题标题】:wait and notify with implementing Runnable and extending Thread example通过实现 Runnable 和扩展 Thread 示例等待并通知
【发布时间】:2015-04-01 18:25:31
【问题描述】:

我正在实现逻辑来理解等待和通知工作我发现了一些我无法分析的东西,当我用线程扩展类然后等待和通知按预期工作但是当我实现可运行接口时输出会有所不同

public class AdderThread extends Thread {

int total;

@Override
public void run() {

    synchronized (this) {
        for (int i = 0; i < 1000; i++) {
            total += i;
        }

        notify();
    }

}





public class WaitNotify {

public static void main(String[] args) {

    AdderThread addrTh = new AdderThread();
    addrTh.start();
    // -1243309312

    System.out.println("Total without Wait() " + addrTh.total);


}

}

当实现 Runnable 给我正确的答案时,意味着它正在等待线程完成任务,但是当我使用扩展线程时,它给我的答案为 0,即它没有等待线程完成任务。

public class WaitNotify {

public static void main(String[] args) {

    AdderThread addrTh = new AdderThread();
    addrTh.start();
    // -1243309312

    System.out.println("Total Before Wait " + addrTh.total);
    synchronized (addrTh) {

        try {
            System.out.println("Waiting for Sum...");
            addrTh.wait();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("Total " + addrTh.total);
    }

}

}

【问题讨论】:

  • 一开始你写的扩展是工作的,可运行的不是。最后,您说的是可运行的作品,而不是可扩展的作品。你读过你输入的内容吗?
  • 对不起...我的意思是说,当我扩展线程时,如果没有 wait(),我的结果无法正确运行,因为线程仍在运行。但是,当我实现 Runnable 时,我的结果正在运行正确不使用 wait()

标签: java multithreading


【解决方案1】:

您的新线程可以在主线程调用 `wait() 之前调用 notify()。" 在这种情况下,wait() 调用将永远等待,因为如果其他线程还没有,则 notify() 根本不会做任何事情等待它。

wait()notify() 是低级操作,旨在以非常特定的方式使用:

更多信息请参见Java wait() does not get waked by notify()


实现Runnable的情况和扩展Thread的情况之间的区别在于this在第一种情况下指的是匿名内部类,它指的是@987654328 @object 在后一种情况下。

这很重要,因为线程机器出于自己的目的使用 wait() 和 notify()。因此,如果您的wait() 调用来得太晚而无法被代码中的notify() 调用唤醒,它仍可能被库代码中的notify() 唤醒(例如,当线程终止时)。实现 Runnable 时不会发生这种情况,因为库没有理由通知它。

【讨论】:

  • 你的意思是说,在runnable的情况下,即使我们不调用wait(),它也会被自动调用。能不能给我简单的介绍一下谢谢。
  • 没有。我是说Thread 类使用wait()notify()。如果您的应用程序使用自定义 run() 方法定义了 Thread 的子类,并且您的 run() 方法调用 this.wait(),则可以通过库中的 notify() 调用将其唤醒。如果您的应用程序使用调用 this.wait() 的 run() 方法定义了一个匿名内部类,则它只能由您自己的代码唤醒。
猜你喜欢
  • 2011-02-16
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 2011-01-22
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多