我想启动很多任务来在 +-42Mio 记录的数据库上运行。我想以 5000 条记录/时间的批次运行此程序(结果为 850 个任务)。
我还想限制 java 开始为我执行此操作的线程数(最多 16 个),并且我正在使用当前代码来完成此任务:
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);
带线程的部分不应该在那里,我假设你把它放在那里只是为了展示你以前是如何拥有它的?
Update:是的,之后您不需要代码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..
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)