使用执行器时如何同时启动线程?

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

我写了下面的代码:

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);

据我执行代码后的理解:

es.submit(new ArrayReader(arrayHolder));

新线程可以开始执行了。

我想允许仅在提交所有任务时才启动线程。

我知道如果我使用CountDouwnLatch我可以实现它。但是我想知道如果我使用 ExecutorServise.

可以实现吗

您可以使用invokeAll方法。来自文档:

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;

更新:

实际上,您不能依赖任务开始执行的时间和任务顺序。如果您提交了所有任务,则无法确定它们会在一定时间内或在某些事件之前执行。它取决于线程调度,你无法控制它的行为。即使您同时提交所有任务,也不意味着它们会同时执行。