最近項目上用到java多線程和線程池,一致在糾結怎麼判斷線程池中的全部線程任務都執行完畢,當線程池1中的全部線程都執行完成再執行線程池2中的線程,如今終於有了點眉目,整體思路就是先執行shutdown,循環判斷是否全部線程任務已關閉,上代碼:java
ExecutorService service = Executors.newFixedThreadPool(poolSize); ApRunnable apR = new ApRunnable(totalCount, pageSize, totalPage); for(int i=0; i<threadSize; i++) { service.execute(apR); } /* * Initiates an orderly shutdown in which previously submitted * tasks are executed, but no new tasks will be accepted. */ service.shutdown(); /* * if all task still not finish, sleep 5 seconds and check again */ while(!service.isTerminated()) { try { service.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { e.printStackTrace(); } }