等待线程池所有任务执行完成实例
关键字: 线程池
在项目中,线程池执行一个任务后,要把结果放到集合中。调用线程池shutdown方法,就去遍历集合,就有可能出现java.util.ConcurrentModificationException异常。因为调用shutdown方法,只是告诉线程池关闭后不能加入新线程,队列中的线程则依次执行完。各个子线程依旧有可能在运行任务。
当然也可以使用CountDownLatch实现,但是麻烦了些。
要等待所有子线程执行完后,再去遍历集合。才是正确方法。用线程池的awaitTermination方法就可以实现等待线程池所有任务执行完成。
具体实例如下:
public static void main(String[] args){ final ThreadPoolExecutor pool = new ThreadPoolExecutor(5, 100, 1, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(5000),new ThreadPoolExecutor.CallerRunsPolicy()); int total=0; final AtomicLong count=new AtomicLong(); final Set<String> resultSet=new CopyOnWriteArraySet<String>(); for(long i=0;i<=100000;i++){ try{ pool.execute(new Runnable() { @Override public void run() { try{ Thread.sleep(20l); resultSet.add(count.addAndGet(1)+""); }catch(Exception e){ //ignore } } }); }catch(Exception e){ e.printStackTrace(); } total++; } pool.shutdown(); System.out.println(pool.getActiveCount()); try{ pool.awaitTermination(5, TimeUnit.MINUTES); }catch(Exception e){ } System.out.println(pool.getActiveCount()); for(String s : resultSet){ System.out.println(s); } } |
线程池调用shutdown方法后,查看活动的子线程getActiveCount,结果为100.表明调用shutdown方法,只是不再接受新的任务,以前运行的任务将继续执行,待完成后再销毁线程池。
线程池调用awaitTermination方法后,查看活动的子线程getActiveCount,结果为0.
本文固定链接: http://www.chepoo.com/waiting-for-the-thread-pool-all-the-tasks-completed-instance.html | IT技术精华网
【上一篇】java set线程安全异常
【下一篇】Java compiler level does not match the version of the installed Java project facet
【下一篇】Java compiler level does not match the version of the installed Java project facet