Why isn't the current thread waiting for other threads before returning a value?
I have two themes. In each of them, I run the scheduler.
Thread one = new Thread(
() -> scheduler.scheduleAtFixedRate(eventMaker, 0, 1, MICROSECONDS)
);
Thread two = new Thread(
() -> timeChecker.schedule(timeAnalyser, 1, TimeUnit.SECONDS)
);
Then I run them and call join()
on them to make the method they are initialized in to wait for them to complete before returning the return value.
threads = new Thread[2];
threads[0] = one;
threads[1] = two;
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
for (int i = 0; i < threads.length; i++) {
threads[i].join();
}
return a;
But still the method in which they are called does not wait for them. It returns instantly despite being called join()
. How can I wait for threads before returning?
Your help would be appreciated.
source to share
Assuming scheduler
and timeChecker
are ScheduledExecutorService
s, your code does what it is supposed to do.
Both schedule
and scheduleAtFixedRate
are asynchronous, as they are planning to work in a separate thread in the future. They both return immediately.
Your two streams, one
and two
, are useless here. You seem to want to receive ScheduledFuture
from schedule
and call get
on calls .
ScheduledFuture<?> schedulerFuture = scheduler.scheduleAtFixedRate(eventMaker, 0, 1, MICROSECONDS);
ScheduledFuture<?> timerFuture = timeChecker.schedule(timeAnalyser, 1, TimeUnit.SECONDS);
schedulerFuture.get();
timerFuture.get();
The ScheduledFuture
callback schedule
will return from get
after the first execution completes.
Refunds ScheduledFuture
for the call scheduleAtFixedRate
will get
only be returned from if canceled or if ScheduledExecutorService
completed.
Otherwise, the task will terminate only by canceling or terminating the executor.
source to share