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
This kind of simple notification is what
Object.wait()andObject.notify()are intended for.In your updater thread, you have
And then in your checking thread, have
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.