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.
精彩评论