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

In the main method, the child thread is started using the java 1.5 executor service mechanism. How to make the main thread wait for the child thread to finish?

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(); } } } 
+6
source share
1 answer

As a rule, you should not distribute Thread directly, as this simply leads to confusion, as here.

Your TestThread never starts, so you cannot join it. All he does is act like Runnable (which is exactly what you should use).

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 5.0 appeared in Java 1.4.2, followed by Java 6 and Java 7.

+9
source

Source: https://habr.com/ru/post/897038/


All Articles