Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join a thread that was started using executor service?

In main method a child thread gets started using java 1.5 executor service mechanism. How can i make main thread to wait until the child thread gets completed ?

public class MainClass {

    public static void main(String[] args) {
        ExecutorService executorService=null;
        try {
            executorService=Executors.newFixedThreadPool(1);
            executorService.execute(new TestThread());
            System.out.println("Main program exited...");
        } catch (Exception e) { 
            e.printStackTrace();
        } finally {
            executorService.shutdown();
        }
    }
}

public class TestThread extends Thread {

    public TestThread() {
    }

    public void run() {
        try {
            for (int i=0;i<10;i++) {
                System.out.println(i);
                TimeUnit.SECONDS.sleep(5);
            }
        } catch (InterruptedException e) { 
            e.printStackTrace();
        }
    }
}
like image 548
Hari Avatar asked Sep 10 '11 10:09

Hari


1 Answers

As a rule of thumb, you should not extend Thread directly as this just leads to confusion, as it has here.

Your TestThread is never started so you cannot join with it. All it is doing is actings as a Runnable (which is what you should use instead).

If you want to wait for the task to complete.

Future future = executorService.submit(new TestRunnable());

// wait for the task to complete.
future.get();

BTW: After Java 1.4.2 came Java 5.0 followed by Java 6 and Java 7.

like image 196
Peter Lawrey Avatar answered Sep 18 '22 12:09

Peter Lawrey