Search code examples
javamultithreadingexecutorservicecountdownlatch

how to know the exact time thread requires to finish


I have two threads t1 and t2. Both of them make some calculations and i am tryin to block the main thread till t1 and t2 finish. I used .awaitTermination() as seen below, but the problem is, despit it is an if-statement, the .awaitTermination() goes in an infinite loop.

please help me to find wyh that is happening. and should i specify an amount of time without knowing the exact time the t1 and t2 require to finish?

 executor.execute(new RunnableClass(bgr,3))
 executor.execute(new RunnableClass(bgr,7))
 executor.shutdown();

if (executor.awaitTermination(3, TimeUnit.SECONDS)) {
    print("terminated")
}

Solution

  • If you use Java 8, you can use CompletableFuture<T> instead. They define some useful methods like join to wait for their execution and chaining them together. Your example would look like this:

    final CompletableFuture<Void> future1 = CompletableFuture.runAsync(new RunnableClass(bgr, 3), executor);
    final CompletableFuture<Void> future2 = CompletableFuture.runAsync(new RunnableClass(bgr, 7), executor);
    CompletableFuture.allOf(future1, future2).join(); // blocks until both finished
    executor.shutdown();
    

    A great introduction can be found here.