Java Thread Executor Execute runConcurrently(Runnable... tasks)

Here you can find the source of runConcurrently(Runnable... tasks)

Description

run Concurrently

License

Open Source License

Declaration

public static void runConcurrently(Runnable... tasks) throws ExecutionException, InterruptedException 

Method Source Code


//package com.java2s;
// This software is released under the Apache License 2.0.

import java.util.*;
import java.util.concurrent.*;

public class Main {
    public static void runConcurrently(Runnable... tasks) throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(tasks.length);
        CountDownLatch allTasksStarted = new CountDownLatch(tasks.length);
        try {/*from  ww  w . j  a v  a 2s  .com*/
            List<Future<?>> futures = new ArrayList<>();
            for (Runnable task : tasks) {
                futures.add(executor.submit(() -> {
                    sync(allTasksStarted, 1000);
                    task.run();
                }));
            }
            for (Future<?> future : futures) {
                future.get();
            }
        } finally {
            executor.shutdownNow();
        }
    }

    public static void sync(CountDownLatch barrier, long timeoutMillis) {
        barrier.countDown();
        await(barrier, timeoutMillis);
    }

    public static void await(CountDownLatch barrier, long timeoutMillis) {
        try {
            barrier.await(timeoutMillis, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Related

  1. invokeAsync(Runnable runnable)
  2. invokeLater(Runnable runnable)
  3. invokeOnBackgroundThread(Runnable runnable)
  4. run(Runnable target)
  5. runConcurrently(final Runnable[] threads)
  6. runInBackground(final Runnable task)
  7. runInBackground(Runnable run)
  8. runInNewThread(Runnable task)
  9. runOnUI(Runnable runnable)