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();
}
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With