0

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?

Mateus Ramos
  • 190
  • 2
  • 12
  • 3
    You should be calling `.start()` and not `.run()` on the Thread objects, no? – Hovercraft Full Of Eels Jul 07 '20 at 21:35
  • 2
    Your code is single-threaded. You are calling `t.run()`, which will call the thread body and return. You have to call `t.start()` instead to start the thread. – Burak Serdar Jul 07 '20 at 21:37
  • O have probably misread the documentation then, I was thinking run() would call start() but now I see i doesnt make sense and its the other way around. I'll test the code again asap, thanks for the answers – Mateus Ramos Jul 07 '20 at 21:46

0 Answers0