views:

40

answers:

3

I have about 4 threads. One thread keeps checking some data that the other thread is updating. The others are doing some processing in the background. All have been started at this point.

My question is when the checking thread sees that the data has not been updated yet I currently sleep for a little bit but is there any way for me to tell the system to back to executing the thread that does the updating?

That or is there any way I can put something like a listener on the data(a String) and once its updated an event will fire that will do what it needs to do?

I tried using yield() and it seemed to just keep returning to the thread I called yield() from.

Thanks

A: 

You should consider wait() and notify().

VeeArr
+1  A: 

You cannot force a given thread to run. You can, however, put your checking thread to sleep and have your producing thread notify it when data is ready.

This is a classic "producer/consumer" problem, and java.lang.Object has methods to help you implement this (wait/notify/notifyAll). For higher level constructs, check out java.util.concurrent

dty
+2  A: 

This kind of simple notification is what Object.wait() and Object.notify() are intended for.

In your updater thread, you have

void updateData() {
    synchronized (theData) {
       theData.doSomeUpdate();
       theData.notifyAll(); // tell other threads of a change
    }
}

And then in your checking thread, have

void waitForUpdates() {
    synchronized (theData) {
       while (notCancelled) {
          theData.wait();  // wait for notification
          handleUpdate(theData);
       }
    }        
}

Don't use Thread.sleep() since you can't really wake up the thread, unless you interrupt it, and that's a little nasty. Instead, use the wait/notify process above.

You can also look at passing notifications via an explicit BlockingQueue that is shared between the threads. The updater thread puts events in the queue, and the checker thread uses take() to fetch update events from the queue, waiting if there are no updates in the queue.

The difference with this scheme is that the updater thread can pass specific information about what has changed, rather than just saying "something changed", as is the case with wait/notify.

Also, the thread is notified of each update explicitly, so no updates are missed. It's also more flexible than wait/notify, since notification of updates does not require a lock on the data.

mdma
That makes sense thanks
Mike