java - 如何在使用执行器的同时启动线程?

标签 java multithreading concurrency executorservice

我写了以下代码:

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;

更新:

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

关于java - 如何在使用执行器的同时启动线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31904378/

相关文章:

mysql - 防止 MySQL 和 Devart MySQL Connector 中的并发冲突

java - 我已经在 Eclipse 中更改了内存大小,但仍然收到 java.lang.OutOfMemoryError

python - 使用python控制线程中的循环

c# - 线程池最大线程数

java - 如何在Java SE7中实例化Runnable类型?

c++ - 为什么不在 pop 之后运行任务并返回 true?

concurrency - Go 如何决定何时在 goroutine 之间进行上下文切换?

java - servlet 不显示连接两个表的所有匹配结果

java - 递归鞍背 - 在 Java 中搜索已排序的二维数组中的元素

java - 如何在运行时使用 Annotation Processing API?