java中的多线程处理并监听全部线程执行完成
1,多线程的创建和使用
int max=500; ExecutorService fixedThreadPool = Executors.newFixedThreadPool(max); for (int i = 0; i < max; i++) { final int index = i; fixedThreadPool.execute(new Runnable() { @Override public void run() { try { logger.info("线程开始处理数据:"+index); logger.info(Thread.currentThread().getName()+"->执行开始"); //业务方法 changeCollectThread(allList,index); logger.info(Thread.currentThread().getName()+"->执行完成"); } catch (Exception e) { e.printStackTrace(); } } }); } fixedThreadPool.shutdown(); System.out.println("主线程输出");
此时,程序中会创建500个线程并行处理业务方法。
2,上述创建方式中的主线程无法在子线程执行完成之后执行,若想实现顺序执行需添加:
fixedThreadPool.shutdown(); //设置线程最大等待时长,60秒 if(!pool.awaitTermination(60, TimeUnit.SECONDS)){ pool.shutdownNow(); }
参考:
3,推荐使用此种方式,CountDownLatch:
int max = 500; CountDownLatch countDownLatch = new CountDownLatch(max); ExecutorService fixedThreadPool = Executors.newFixedThreadPool(max); for (int i = 0; i < max; i++) { final int index = i; fixedThreadPool.execute(new Runnable() { @Override public void run() { try { logger.info("线程开始处理数据:"+index); logger.info(Thread.currentThread().getName()+"->执行开始"); //业务方法 changeCollectThread(allList,index); logger.info(Thread.currentThread().getName()+"->执行完成"); } catch (Exception e) { e.printStackTrace(); }finally { countDownLatch.countDown(); } } }); } try { countDownLatch.await(); } catch (InterruptedException e) { e.printStackTrace(); } fixedThreadPool.shutdown(); logger.info(Thread.currentThread().getName()+"->全部任务执行完成");