简体   繁体   中英

Synchronizing threads java

I'm new to multithreading and have some trouble synchronizing two threads.

I'm reading data from a tag which I then want to do calculations on in another thread, so my phone can continue communicating with the tag and not have to wait for the calculations to be done. The relevant code basically looks like this:

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
}

CalculationThread:

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

I know that you need to put wait and notify in a synchorized block or add the synchronized tag to the method, but I still can't seem to figure out how to correclty synchronize these threads.

Thanks in advance.

This looks suspicious:

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

That notify() call happens in the run() method of a CalculationThread instance. There's no object specified on which to call notify() , so you are implicitly calling this.notify() (ie, you are calling notify() on a CalculationThread instance.)

The corresponding wait() also does not specify any object, so there, you are implicitly calling this.wait() . But what is this ? The call happens in a method named f() , but what class does f() belong to?

A call to o.notify() in one thread will have no effect on some other thread that's waiting in a p.wait() call if o and p are different objects.

You said you were having some trouble synchronizing, but you never said what the "trouble" actually was. If the trouble was, wait() never returned, then is it possible that the object you notify() ed was not the same object that was wait() ing?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM