简体   繁体   中英

Java Executer Service

I have a database result which creating 500 records per one call 500, then next 500, then next

I need to run a each records which different thread to do the specific task

My examples as follows

List<Users> users =  find 500 users 

ExecutorService executor = 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
}

}

My problem is that before finishing current executer service it getting the next 500 users and trying to start processing ,I need to stop that and until first 500 records processed then start next pool

You should try to have code that at least compiles. Anyway it sounds like you could use a CountDownLatch to wait for the threads to complete before moving onto the next 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM