新的多线程 - 如何在java中使用wait()和notify()? [英] new to multithreading- how to use wait() and notify() in java?

查看:144
本文介绍了新的多线程 - 如何在java中使用wait()和notify()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个包含2个类的程序,一个控制器和一个执行大量计算的类。控制器创建另一个类的几个实例,然后告诉他们所有人开始计算(并行)。它们各自在完成后返回,控制器恢复,然后,一段时间后,控制器将新数据传递给它们,并让它们再次运行计算。

理想情况下,我可以调用带参数的start(),但这是不可能的,所以控制器调用计算器中的一个方法,将数据存储在全局中,然后启动计算线程并返回,直到我再次尝试启动线程为止,它告诉我线程已经死了。所以我试图使运行成为一个无限循环,等待通知,运行计算,将结果存储在全局中,以便控制器可以在以后检索它们,然后重新开始等待。所以类似于:

I'm trying to write a program with 2 classes, a controller and a class that does a lot of computation. The controller creates a couple instances of the other class, then tells them all to start their calculations (in parallel). They each return when they are finished, and the controller resumes, and then, some time later, the controller passes them new data, and has them run the calculation again.
Ideally, I would be able to call start() with parameters, but that isn't possible, so the controller calls a method in the calculator that stores the data in a global, and then starts the calculation thread and returns, which works until I try to start the thread again, and it tells me the thread is dead. So I'm trying to make the run an infinite loop that just waits until it is notified, runs the calculations, stores the results in a global so the controller can retrieve them later, then resumes waiting. So something like:

//in controller:
Calculator calc=new Calculator();
calc.runCalculations(data);
while(calc.isCalculating()){
    //do nothing
}
System.out.println("results: "+calc.getAnswer());
calc.runCalculations(data2);

//in calculator:
public runCalculations(Data data){
    globalData=data;
    this.notify();
}
public void run(){
    while(true){
        synchronized(this){
            wait();
        }
        calculating=true;
        globalData=calculate(globalData);
        calculating=false;
    }
}


推荐答案

你在调用 notify()之前,需要在上获取监视器。
另外,当你调用 wait()时,你应该在一个循环中这样做,检查条件以确定你没有经历过虚假的唤醒。

You need to obtain the monitor on this before you call notify(). Also, when you call wait() you should do so in a loop that checks a condition to be certain that you did not experience a spurious wakeup.

public runCalculations(Data data){
    globalData=data;
    synchronized(this) {
        calculating=true;
        this.notify();
    }
}
public void run(){
    while(true){
        synchronized(this){
            calculating=false;
            while(!calculating) {
                wait();
            }
        }
        globalData=calculate(globalData);
    }
}

一般来说,大多数人会建议不要使用wait /通知并建议您使用Executor或至少使用BlockingQueue。但这两者都需要你重新设计你当前的想法。

In general, most people would advise against using wait/notify and instead recommend you use an Executor or at the very least a BlockingQueue. But both of those would require you to redesign what you are currently thinking.

这篇关于新的多线程 - 如何在java中使用wait()和notify()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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