Catheryan
Catheryan

Reputation: 111

How to start two process at the same time and then wait both completed?

I want to start two process at the same time and make sure complete them all before proceeding other steps. Can you help? I already tried Thread, it can't start two at the same time and wait until been done.

    final CyclicBarrier gate = new CyclicBarrier(3);
    Thread r2 = new Thread()
    {

        public void run()
        {
            try
            {
                int i = 0;
                while (i < 3)
                {
                    System.out.println("Goodbye, " + "cruel world!");
                    Thread.sleep(2000L);
                    i++;
                    gate.await();
                }
            }
            catch (InterruptedException | BrokenBarrierException iex)
            {
            }
        }
    };

    Thread r3 = new Thread()
    {
        public void run()
        {
            try
            {
                int i = 0;
                while (i < 3)
                {
                    System.out.println("Goodbye, " + "cruel world!");
                    Thread.sleep(2000L);
                    i++;
                    gate.await();
                }
            }
            catch (InterruptedException | BrokenBarrierException iex)
            {
            }
        }
    };

    r2.start();
    r3.start();
    gate.await();
    System.out.println("Donew");

Upvotes: 0

Views: 541

Answers (3)

erickson
erickson

Reputation: 269637

Your problem is that you are repeatedly waiting for three parties, but only two threads are calling await() repeatedly. I would expect your code to immediately print, "Goodbye, cruel world!" twice, and "Done", then hang, because the loops are waiting for a third thread to invoke await() again, but the main thread has now terminated.

One solution is for your main thread to loop, invoking await() the same number of times that your task does. But that would be kind of ugly.

I'd suggest using the invokeAll() method of an ExecutorService. This will submit your tasks to the service at (approximately) the same time, then block until all tasks complete. If you want to try to improve the simultaneity of the task commencing, you could add a CyclicBarrier, but it looks like you are more concerned with when the tasks end, and invokeAll() will take care of that for you.

final class Sample
  implements Callable<Void>
{

  private static final int ITERATIONS = 3;

  private static final long AVG_TIME_MS = 2000;

  public static void main(String[] args)
    throws InterruptedException
  {
    List<Sample> tasks = Arrays.asList(new Sample(), new Sample());
    ExecutorService workers = Executors.newFixedThreadPool(tasks.size());
    for (int i = 1; i <= ITERATIONS; ++i) {
      /* invokeAll() blocks until all tasks complete. */
      List<Future<Void>> results = workers.invokeAll(tasks);
      for (Future<?> result : results) {
        try {
          result.get();
        }
        catch (ExecutionException ex) {
          ex.getCause().printStackTrace();
          return;
        }
      }
      System.out.printf("Completed iteration %d.%n", i);
    }
    workers.shutdown();
    System.out.println("Done");
  }

  @Override
  public Void call()
    throws InterruptedException
  {
    /* The average wait time will be AVG_TIME_MS milliseconds. */
    ThreadLocalRandom random = ThreadLocalRandom.current();
    long wait = (long) (-AVG_TIME_MS * Math.log(1 - random.nextDouble()));
    System.out.printf("Goodbye, cruel world! (Waiting %d ms)%n", wait);
    Thread.sleep(wait);
    return null;
  }

}

Notice how I spiced things up with a random wait time. Yet, invokeAll() waits until all of tasks in that iteration complete.

Upvotes: 3

Matthias247
Matthias247

Reputation: 10396

You can use Thread.join()to wait until your subprocesses/threads have finished. You should not need CyclicBarrier.

Upvotes: 3

user1812855
user1812855

Reputation: 3

  1. It's impossible for the single processor machines.
  2. Even if you find lot of answers on threads its not gonna start two process at the same time
  3. If you accept the Relative Simultanity that will be easy.

Upvotes: -3

Related Questions