多线程最佳实践:约束任务newFixedThreadPool

我想启动许多要在+

-42Mio记录的数据库上运行的任务。我想批量运行5000条记录/时间(结果是850个任务)。我还想将线程数限制为16个,因此Java开始为我执行此操作,并且我正在使用当前代码来完成此任务:

 ExecutorService executorService = Executors.newFixedThreadPool(16);

for (int j = 1; j < 900 + 1; j++) {

int start = (j - 1) * 5000;

int stop = (j) * 5000- 1;

FetcherRunner runner = new FetcherRunner(routes, start, stop);

executorService.submit(runner);

Thread t = new Thread(runner);

threadsList.add(t);

t.start();

}

这是正确的方法吗?特别是当我有一种印象,即Java会触发所有任务…(FetcherRunner实现runnable

回答:

使用ExecutorService的第一部分看起来不错:

...

FetcherRunner runner = new FetcherRunner(routes, start, stop);

executorService.submit(runner);

带有Thread的部分不应该在那儿,我假设您在那儿只是为了展示您以前的经历?

是的,您不需要之后的代码executorService.submit(runner),最终将产生大量线程。如果您的目标是在循环后等待所有提交的任务完成,则可以Future在提交任务时获取参考,然后等待Future,如下所示:

ExecutorService executorService = Executors.newFixedThreadPool(16);

List<Future<Result>> futures = ..;

for (int j = 1; j < 900+ 1; j++) {

int start = (j - 1) * 5000;

int stop = (j) * 5000- 1;

FetcherRunner runner = new FetcherRunner(routes, start, stop);

futures.add(executorService.submit(runner));

}

for (Future<Result> future:futures){

future.get(); //Do something with the results..

}

以上是 多线程最佳实践:约束任务newFixedThreadPool 的全部内容, 来源链接: utcz.com/qa/420024.html

回到顶部