I have a Runnable that keep calling an external API until the result is ready (polling?).
I initialize the Threads as null, then, if the service has to be called I then assign a new Thread(runnable)
to thread an call run()
.
I'm doing that way because after firing every thread I use join() to get the general result.
My problem is that the threads seems to be running synchronously instead of asynchronously, I've put a sysout at the start and the end of the runnable, and they only start when the one called befored finishes.
private Runnable runnable(final String threadName) {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("started " + threadName + "at: " + System.currentTimeMillis());
// polling goes here and updates database after finished
System.out.println("finished " + threadName + "at: " + System.currentTimeMillis());
}
};
return r;
}
public void myMethod() {
// currently i'm using 5 threads, but I guess this example is enough
Thread threadFoo = null;
Thread threadBar = null;
// check db for conditions
if( someCondition ) {
threadFoo = new Thread(runnable("FOO"));
threadFoo.run();
}
if( someOtherCondition ) {
threadBar = new Thread(runnable("BAR"));
threadBar.run();
}
if(threadFoo != null && threadFoo .isAlive()) {
threadFoo .join();
}
if(threadBar!= null && threadBar.isAlive()) {
threadBar.join();
}
// more code that has to be done after every thread finished
}
The output shows that threads only starts exactly when the previous called thread finishes, what am I doing wrong?