【发布时间】:2021-02-08 04:59:09
【问题描述】:
我正在尝试在我的程序中引入并发性。程序结构是这样的:
ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(5);
List<String> initialData = dao.fetchFromDB("input");
Queue queue = new MyQueue();
queue.add(initialData);
while(queue.length() > 0) {
int startingLength = queue.length();
for (int i = 0; i < startingLength; i++) {
String input = queue.remove();
if(input.equals("some value")) {
missionAccomplished = true;
break;
} else {
MyRunnable task = new MyRunnable(input, queue, dao);
executor.execute(task);
}
}
if(missionAccomplished) {
break;
}
executor.shutdown();
}
所以队列中包含了需要一一处理的数据。在while循环中,我运行一个for循环,它依次从队列中挑选数据并对其进行一些检查,如果检查失败,我将使用这些数据创建一个可运行的任务并将其交给执行程序(因为数据库操作很耗时,我想为此使用并行性)。 for 循环在给定的 while 迭代中仅选择特定长度的数据。 我想要实现的是,只有在当前迭代中提交给执行程序的所有任务都完成时,'while'循环才会进入下一次迭代。
如何做到这一点?
【问题讨论】:
标签: java concurrency parallel-processing executorservice