gstackoverflow
gstackoverflow

Reputation: 36994

How to start threads at the same time when I use executors?

I have wrote following code:

ExecutorService es = Executors.newCachedThreadPool();
long start= System.currentTimeMillis();
ArrayHolder arrayHolder = new ArrayHolderBySynchronized();
List<Runnable> runnables = new ArrayList<>();
for (int i = 0; i < readerThreadCount; i++) {            
    es.submit(new ArrayReader(arrayHolder));
}
for (int i = 0; i < writerThreadCount; i++) {
    es.submit(new ArrayWriter(arrayHolder));
}
es.shutdown();
boolean finshed = es.awaitTermination(1, TimeUnit.MINUTES);
long finished= System.currentTimeMillis();
System.out.println(finished-start);

As I understand after execution code:

es.submit(new ArrayReader(arrayHolder));

new thread can begun execute.

I want to allow to start thread only when I submit all tasks.

I know that I can achieve it if I use CountDouwnLatch. But I want to know can I achieve it if I use ExecutorServise.

Upvotes: 2

Views: 2604

Answers (1)

ka4eli
ka4eli

Reputation: 5424

You can use invokeAll method. From docs:

Executes the given tasks, returning a list of Futures holding their status and results when all complete. Future.isDone is true for each element of the returned list. Note that a completed task could have terminated either normally or by throwing an exception. The results of this method are undefined if the given collection is modified while this operation is in progress.

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
        throws InterruptedException;

UPDATE:

Actually, you can't rely on the time when task execution starts and order of tasks. If you submitted all tasks you can't be sure that they will be executed in some amount of time or before some event. It depends on thread scheduling, you can't control it's behaviour. Even if you submit all tasks at the same time it does not imply that they will be executed at the same time.

Upvotes: 2

Related Questions