Piskvor Piskvor - 2 years ago 125
Java Question

How to make a Java thread wait for another thread's output?

I'm making a Java application with an application-logic-thread and a database-access-thread.
Both of them persist for the entire lifetime of the application. However, I need to make sure that initially the app thread waits until the db thread is ready (currently determined by polling a custom method

I wouldn't mind if app thread blocks until the db thread was ready.

doesn't look like a solution - the db thread only exits at app shutdown.

while (!dbthread.isReady()) {}
kind of works, but the empty loop consumes a lot of processor cycles.

Any other ideas? Thanks.

Answer Source

I would really recommend that you go through a tutorial like Sun's Java Concurrency before you commence in the magical world of multithreading.

There are also a number of good books out (google for "Concurrent Programming in Java", "Java Concurrency in Practice".

To get to your answer:

In your code that must wait for the dbThread, you must have something like this:

//do some work
    while (!dbThread.isReady()){
//continue with work after dbThread is ready

In your dbThread's method, you would need to do something like this:

//do db work
    //set ready flag to true (so isReady returns true)
    ready = true;
//end thread run method here

The objectYouNeedToLockOn I'm using in these examples is preferably the object that you need to manipulate concurrently from each thread, or you could create a separate Object for that purpose (I would not recommend making the methods themselves synchronized):

private final Object lock = new Object();
//now use lock in your synchronized blocks

To further your understanding:
There are other (sometimes better) ways to do the above, e.g. with CountdownLatches, etc. Since Java 5 there are a lot of nifty concurrency classes in the java.util.concurrent package and sub-packages. You really need to find material online to get to know concurrency, or get a good book.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download