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();
    }
}
posted @ 2021-08-30 15:27  yongfengnice  阅读(510)  评论(0编辑  收藏  举报