How to join one thread with another in java?

I have one main thread that starts another 10 other threads. I want the main thread to be finished only after the termination of all other threads. So I have to call join () for the other 10 threads before or after they start. For example:

// in the main() method of Main thread
Thread [] threads = new Thread[10];
for(int i = 0; i < 10; i++) {
    // ParserThread() is a runnable thread
    threads[i] = new Thread(new ParserThread());
    threads[i].join();
    threads[i].start();
}
System.out.println("All threads have been finished"); // line no. 9
  • So, as in the above example, I have to call join () before starting () or after starting ().
  • Will the control return to line no. 9 only after the completion of all threads.
  • When the method of starting any thread is executed, then this thread will die or remain alive. If this happens, then how to end all threads when their start method is finished means that the control returns to line no. nine
+3
5

join() . join() , , . :

// in the main() method of Main thread
Thread [] threads = new Thread[10];
for(int i = 0; i < 10; i++) {
    // ParserThread() is a runnable thread
    threads[i] = new Thread(new ParserThread());
    threads[i].start();
}
System.out.println("All threads have been started");
for(int i = 0; i < 10; i++) {
    threads[i].join();
}
System.out.println("All threads have been finished");
+7

Thread, join(), java.util.concurrent, CyclicBarrier:

, - . CyclicBarriers , . , .

, Thread.join() .

+6

, ThreadPoolExecutor :

ThreadPoolExecutor executor = new ThreadPoolExecutor(0, 10, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

for (int i = 0; i < 10; i++)
    executor.execute(new ParserThread());

try {
    executor.shutdown();
    executor.awaitTermination(10, TimeUnit.MINUTES);
} catch (final InterruptedException e) {
     // handle
}

, , - .

+5

you must first start the entire stream, and then start joining them. Join will return direct if called before the start of the stream.

+1
source

The point may be that you want to join a thread group. See Javadoc for

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorCompletionService.html

 void solve(Executor e,
              Collection<Callable<Result>> solvers)
     throws InterruptedException, ExecutionException {
       CompletionService<Result> ecs
           = new ExecutorCompletionService<Result>(e);
       for (Callable<Result> s : solvers)
           ecs.submit(s);
       int n = solvers.size();
       for (int i = 0; i < n; ++i) {
           Result r = ecs.take().get();
           if (r != null)
               use(r);
       }
   }

For trivial scenarios (single thread) Thread.join () is enough.

0
source

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


All Articles