Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.join() equivalent in executor [duplicate]

I have a newbie question. I have this code:

public class Main 
{

    public static void main(String[] args) throws InterruptedException 
    {
        // TODO Auto-generated method stub
        IntHolder aHolder=new IntHolder();
        aHolder.Number=0;

        IncrementorThread A= new IncrementorThread(1, aHolder);
        IncrementorThread B= new IncrementorThread(2, aHolder);
        IncrementorThread C= new IncrementorThread(3, aHolder);

        A.start();
        B.start();
        C.start();

        A.join();
        B.join();
        C.join();
        System.out.println("All threads completed...");

    }

}

Which will wait for all threads to complete. If I use Executors like this:

public class Main 
{

    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        IntHolder aHolder=new IntHolder();
        aHolder.number=0;

        IncrementalRunable A= new IncrementalRunable(1, aHolder);
        IncrementalRunable B= new IncrementalRunable(2, aHolder);
        IncrementalRunable C= new IncrementalRunable(3, aHolder);

        ExecutorService exec = Executors.newFixedThreadPool(3);
        exec.execute(A);
        exec.execute(B);
        exec.execute(C);
        //Don't know what to do here

        System.out.println("All threads completed...");
    }
}

How can I suspend the main thread to wait for all the threads in the executor to finish, i.e the "All threads completed..." should be printed after the all the threads have done their work?

like image 1000
Mario Stoilov Avatar asked Dec 10 '13 13:12

Mario Stoilov


People also ask

What is thread join ()?

Join is a synchronization method that blocks the calling thread (that is, the thread that calls the method) until the thread whose Join method is called has completed. Use this method to ensure that a thread has been terminated. The caller will block indefinitely if the thread does not terminate.

What is the difference between thread and executor?

A Thread represents something which is responsible for executing your code in parallel, while an Executor is an abstraction for concurrent task execution.

Does join terminate a thread?

join() does not do anything to thread t . The only thing it does is wait for thread t to terminate.

How do I join two threads?

Thread class provides the join() method which allows one thread to wait until another thread completes its execution. If t is a Thread object whose thread is currently executing, then t. join() will make sure that t is terminated before the next instruction is executed by the program.


3 Answers

You shouldn't use executor like this if you want to wait for tasks to finish. What if you don't want/can't shutdown your thread pool executor? This is a more recommended way:

    ExecutorService exec = Executors.newFixedThreadPool(3);
    Collection<Future<?>> tasks = new LinkedList<Future<?>>();

    Future<T> future = exec.submit(A);
    tasks.add(future);
    future = exec.submit(B);
    tasks.add(future);
    future = exec.submit(C);
    tasks.add(future);

    // wait for tasks completion
    for (Future<?> currTask : tasks) {
            try {
                currTask.get();
            } catch (Throwable thrown) {
                Logger.error(thrown, "Error while waiting for thread completion");
            }
        }
like image 100
Lital Kolog Avatar answered Oct 11 '22 12:10

Lital Kolog


executor.shutdown();
while (!executor.awaitTermination(24L, TimeUnit.HOURS)) {
    System.out.println("Not yet. Still waiting for termination");
}

Use shutdown() + awaitTermination() combination.

EDIT:

Based on the comment of @Lital

List<Callable<Object>> calls = new ArrayList<Callable<Object>>();
calls.add(Executors.callable(new IncrementalRunable(1, aHolder)));
calls.add(Executors.callable(new IncrementalRunable(2, aHolder)));
calls.add(Executors.callable(new IncrementalRunable(3, aHolder)));

List<Future<Object>> futures = executor.invokeAll(calls);

NOTE: invokeAll() will not return until all the tasks are completed (either by failing or completing successful execution).

like image 32
Narendra Pathai Avatar answered Oct 11 '22 12:10

Narendra Pathai


We can use below code to join the thread.

 executor.execute(new YouThread());

    try{     
         executor.shutdown();
         while (!executor.awaitTermination(24L, TimeUnit.HOURS)) {
             System.out.println("Not yet. Still waiting for termination");
         }                
    }catch(InterruptedException e){
        e.printStackTrace();
    }
like image 32
Rakesh Singh Balhara Avatar answered Oct 11 '22 12:10

Rakesh Singh Balhara