//逻辑:代码里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();
    }
}

相关文章:

  • 2022-12-23
  • 2021-06-02
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2022-03-01
  • 2022-12-23
  • 2022-02-03
猜你喜欢
  • 2022-01-07
  • 2021-05-19
  • 2022-02-25
  • 2021-10-30
  • 2022-12-23
  • 2021-04-13
  • 2021-08-14
相关资源
相似解决方案