同步线程java



我是多线程的新手,在同步两个线程时遇到了一些问题。

我正在读取标签中的数据,然后我想在另一个线程中对其进行计算,这样我的手机就可以继续与标签通信,而不必等待计算完成。相关代码基本上如下所示:

public void f() {
//...some stuff
for (byte[] data : dataObject) {
byte[] response = tag.transive(data); //exchange data with tag
CalculcationThread calc = new CalculationThread(data, card);
calc.start();
}
card.setReady(true);
wait(); //wait for all calculations to have finished
//do some stuff based on calculations
}

计算线程:

public class CalculationThread extends Thread {
...
@Override
public void run() {
//do calculations, then
if(card.isReady()) {
notify(); //notify main thread that all calculations are complete
}
}
}

我知道你需要在同步块中放入等待和通知,或者在方法中添加同步标记,但我似乎仍然不知道如何正确地同步这些线程。

提前谢谢。

这看起来很可疑:

notify(); //notify main thread that all calculations are complete

notify()调用发生在CalculationThread实例的run()方法中。没有指定要在其上调用notify()的对象,因此您隐式地调用this.notify()(即,您在CalculationThread实例上调用notify()(

相应的wait()也没有指定任何对象,所以在那里,您隐式地调用this.wait()。但什么是this?调用发生在一个名为f()的方法中,但f()属于哪个类?

如果op是不同的对象,则在一个线程中对o.notify()的调用对正在等待p.wait()调用的其他线程没有影响。

你说你在同步时遇到了一些问题,但你从来没有说过";麻烦;实际上是。如果问题是,wait()从未返回,那么您notify()所调用的对象是否可能与wait()所使用的对象不同?

最新更新