zoukankan      html  css  js  c++  java
  • android开发多线程并行执行等待最总结果可使用CountDownLatch类实现

    //逻辑:代码里latch.countDown() 和 latch.await()要同时出现,
    //而且latch.countDown()最总次数n和初始化CountDownLatch(n)相同
    public class Test {
        private int taskNums = 3;
        private volatile CountDownLatch latch = new CountDownLatch(taskNums);
        private List<Task> tasks= new ArrayList(3);//假设有3个自定义任务
        
        private void runTaskBlock(){
            executeTasks();//多线程并行执行任务
            latch.await();//堵塞等待所有任务完成,所以这里不能是ui线程
        }
        //多线程执行任务
        private void executeTasks(){
            ExecutorService executor = Executors.newFixedThreadPool(taskNums);
            for (final Task task : tasks) {
                executor.submit(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            ... //执行耗时任务,比如下载文件等待
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            latch.countDown(); //finally里-1
                        }
                    }
                });
            }
            executor.shutdown();
        }
    }
    
  • 相关阅读:
    echarts 使用demo
    frame外弹出,刷新父页面
    table第一行合并,其余行宽度失效问题
    Redis Desktop Manager
    java web中resources路径
    httpclient
    微信公众号开发: 微信接入(一)
    boot 定时器
    maven自定义archetype
    iOS单例宏
  • 原文地址:https://www.cnblogs.com/yongfengnice/p/15206169.html
Copyright © 2011-2022 走看看