我有一个数据库结果,每个呼叫可创建500条记录 500,然后是下一个500,然后是下一个
我需要在每个记录中运行一条不同的线程来完成特定任务
我的例子如下
List<Users> users = find 500 users
ExecutorService执行程序= Executors.newFixedThreadPool(10);
//for each users
for ( int i =0 ; i<users.size(); i++) {
Runnable worker = new MyWorker(users.get(i));
executor.execute(worker);
}
//MyWorker.java
class MyWorker implements Runnable {
User user;
MyWorker(User user)
this.user = user;
}
@Override
public void run() {
system.out.println("Start);
processCommand(this.user);
system.out.println("End);
}
processCommand(User user){
//processing
}
}
我的问题是,在完成当前的执行程序服务之前,它会获取下500个用户并尝试开始处理,我需要停止该操作,直到处理了前500个记录,然后启动下一个缓冲池
答案 0 :(得分:0)
您应该尝试使用至少可以编译的代码。无论如何,听起来您可以使用CountDownLatch等待线程完成,然后再移至下一个500。
private void myfunc(List<User> users) throws InterruptedException {
ExecutorService executor = Executors.newFixedThreadPool(10);
CountDownLatch countDownLatch = new CountDownLatch(users.size());
for ( int i =0 ; i<users.size(); i++) {
Runnable worker = new MyWorker(users.get(i), countDownLatch);
executor.execute(worker);
}
countDownLatch.await();
}
class MyWorker implements Runnable {
User user;
CountDownLatch countDownLatch;
MyWorker(User user, CountDownLatch countDownLatch) {
this.user = user;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
System.out.println("Start");
processCommand(this.user);
countDownLatch.countDown();
System.out.println("End");
}
void processCommand(User user){
//processing
}
}