简体   繁体   English

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

[英]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 . 我知道如果使用CountDouwnLatch可以实现。 But I want to know can I achieve it if I use ExecutorServise . 但是我想知道如果使用ExecutorServise可以实现这一目标。

You can use invokeAll method. 您可以使用invokeAll方法。 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. Future.isDone对于返回列表的每个元素为true。 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. 即使您同时提交所有任务,也并不意味着它们将在同一时间执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM