异步加载任务的工具类

可以放入多个并行的任务,任务完成通知当前线程回调 onComplete

1 用法如下;

mTasks = new ParallelTasks();
mTasks .add(()->{})
         .add(()->{})
         .add(()->{})
         .start();

2 下面是具体的代现码实:

public class ParallelTasks {

    private final Collection tasks = new ArrayList<>();
    private ExecutorService threads;
    private CountDownLatch latch;
    interface callback{
        void onComplete();
    }
    public callback myCallback;

    public ParallelTasks add(final Runnable task) {
        tasks.add(task);
        return this;
    }

    public void start() throws InterruptedException {
        int num = Runtime.getRuntime().availableProcessors();
        threads = Executors.newFixedThreadPool(num);
        try {
            latch = new CountDownLatch(tasks.size());
            for (final Runnable task : tasks) {
                threads.execute(() -> {
                    try {
                        task.run();
                    } finally {
                        latch.countDown();
                    }
                });
            }
            latch.await();
        } finally {
            threads.shutdown();
            if(myCallback != null){
                myCallback.onComplete();
            }
        }
    }

    public void cancel() {
        tasks.clear();
        if (threads != null) {
            threads.shutdownNow();
        }
        if (latch != null) {
            for (int i = 0; i <= latch.getCount(); ++i) {
                latch.countDown();
            }
        }
    }
}

3 适用场景

启动加载多个异步流程,复制文件,下载多个文件时,可以考虑使用


你可能感兴趣的:(android应用层基础,android,java)