How to wait for all threads to finish, using ExecutorService?

前端 未结 26 2005
你的背包
你的背包 2020-11-22 01:55

I need to execute some amount of tasks 4 at a time, something like this:

ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
while(...) {
    tas         


        
26条回答
  •  借酒劲吻你
    2020-11-22 02:47

    if you use more thread ExecutionServices SEQUENTIALLY and want to wait EACH EXECUTIONSERVICE to be finished. The best way is like below;

    ExecutorService executer1 = Executors.newFixedThreadPool(THREAD_SIZE1);
    for () {
       executer1.execute(new Runnable() {
                @Override
                public void run() {
                    ...
                }
            });
    } 
    executer1.shutdown();
    
    try{
       executer1.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    
       ExecutorService executer2 = Executors.newFixedThreadPool(THREAD_SIZE2);
       for (true) {
          executer2.execute(new Runnable() {
                @Override
                public void run() {
                     ...
                }
            });
       } 
       executer2.shutdown();
    } catch (Exception e){
     ...
    }
    

提交回复
热议问题