最近项目上用到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(); } }