[executorService.invokeAll+Callable实现批量等待任务并发执行】 1.多线程导表案例 2.使用for循环+Future的isDone()实现等待源码分析

 ThreadDto.java // 定义可以并行的任务

import java.util.concurrent.Callable;

public class ThreadDto implements Callable {
    @Override
    public Boolean call() throws Exception {
        // 一个线程里面具体又干10件事
        for (int i = 0; i < 10; i++) {
            System.out.println("xx" + Thread.currentThread().getName());
        }
        return true;
    }
}

Main.java

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // 业务线程池
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        
        // 定义一批任务(5个) 
        List list = new LinkedList<>();
        for (int i = 0; i < 5; i++) {
            list.add(new ThreadDto());
        }

        // 并发执行一批任务,阻塞等着所有的任务执行完毕
        executorService.invokeAll(list);

        //执行完毕就关闭线程池(这个是还会等着任务执行完才真正关闭)
        executorService.shutdown();

        System.out.println("end");
    }
}

/*
xxpool-1-thread-5
xxpool-1-thread-4
xxpool-1-thread-1
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-1
xxpool-1-thread-4
xxpool-1-thread-5
xxpool-1-thread-4
xxpool-1-thread-1
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-1
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-4
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-5
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-3
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
xxpool-1-thread-2
end
 */

笔记:

可以看出 “end”是最后打印的,而任务其实是并行执行的。执行完后再干别的事,这非常方便。比如:导出Excel。

================案例:多线程打表================

package org.example.testMulti;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    /**
     * 存储所有的任务
     */
    private static class GenConfigStruct {
        // 所有的任务
        private Map taskMap = Maps.newConcurrentMap();

        public GenConfigStruct() {
            // 生成一批任务
            for (int i = 0; i < 5; i++) {
                taskMap.put(i, new ExcelData(i));
            }
        }

        public ExcelData getOneData() {
            synchronized (this) {
                Integer[] keys = taskMap.keySet().toArray(new Integer[0]);
                if (keys.length > 0) {
                    return taskMap.remove(keys[0]);
                }

                return null;
            }
        }
    }

    /**
     * 一个任务
     */
    @AllArgsConstructor
    private static class ExcelData {
        private int index;

        public void exportData() {
            try {
                Thread.sleep(10);
                System.out.println(index + ":" + Thread.currentThread().getName());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        GenConfigStruct struct = new GenConfigStruct();

        int threadNum = 5;

        // 开辟5个线程的线程池
        ExecutorService es = Executors.newFixedThreadPool(threadNum);
        List> list = Lists.newArrayList();
        for (int i = 0; i < threadNum; i++) {
            list.add(() -> {
                ExcelData excelData;
                while ((excelData = struct.getOneData()) != null) {
                    excelData.exportData();
                }
                return true;
            });
        }
        // 等待所有的任务完成
        es.invokeAll(list);
        // 完成后关闭线程池
        es.shutdown();
        // 输出完成
        System.out.println("end");
    }
}

其实,就算有守护线程,我们已经判定了任务已经完成了,就可以手动调用System.exit(0);退出程序。

注意:必须在List中写程Callable指定泛型。

invokeAll的原理非常的简单:

public  List> invokeAll(Collection> tasks)
        throws InterruptedException {
        if (tasks == null)
            throw new NullPointerException();

        // 把要执行的任务存起来
        ArrayList> futures = new ArrayList<>(tasks.size());
        try {
            for (Callable t : tasks) {
                RunnableFuture f = newTaskFor(t);
                futures.add(f);
                execute(f);
            }

            // 循环遍历,保证全部执行完毕,有一个没执行完毕,则会因为get而阻塞到这
            for (int i = 0, size = futures.size(); i < size; i++) {
                Future f = futures.get(i);
                
                // 如果没有执行完,就调用get阻塞到这里
                if (!f.isDone()) {
                    // 这里try一下,防止出错导致其它任务也出问题
                    try { 
                        f.get(); 
                    }
                    catch (CancellationException | ExecutionException ignore) {
                    }
                }
            }
            return futures;
        } catch (Throwable t) {
            cancelAll(futures);
            throw t;
        }
    }

原理总结:用isDone判断是否做完,get实现如果没做完就等待着。

比较有意思的是:拿for循环逐个检测,反正有1个没做完,那就是整个任务没完成,大家就都等这,但是不影响其它任务的执行。

你可能感兴趣的:(#,java多线程,java)