欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

ExecutorService 带有返回值的使用

程序员文章站 2022-03-02 08:11:29
...

1、写在前面
java.util.concurrent.ExecutorService 表述了异步执行的机制,可以让任务在后 台执行

2、代码

public static void main(String[] args) {

        List<Integer> integers = new ArrayList<>();
        integers.add(1);
        integers.add(2);
        integers.add(3);
        integers.add(4);
        integers.add(5);
        integers.add(6);
        integers.add(7);
        integers.add(8);
        integers.add(9);
        integers.add(10);

        ExecutorService pool = Executors.newFixedThreadPool(3);

        for (int i = 0; i < integers.size(); i++) {
            Integer integer = integers.get(i);

            Callable<Boolean> run = new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    System.out.println("線程開始,執行的integer"+integer);
                    return Test(integer, pool);
                }
            };

            //可以让线程阻塞
            Future future = pool.submit(run);

            Boolean isPay = false;
            try {
                System.out.println("得到返回值" + (Boolean) future.get());
                isPay = (Boolean) future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }

            if (!isPay) {
                System.out.println("線程結束,退出循環");
                break;
            }

        }

        waitConfirmedTest(pool);
        System.out.println("結束----");
        pool.shutdownNow();

    }

    public static Boolean Test(Integer i, ExecutorService pool) {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (i == 3) {
            return false;
        } else {
            return true;
        }
    }

    private static void waitConfirmedTest(ExecutorService pool) {

        while (true) {
           //isTerminated当调用shutdown()方法后,并且所有提交的任务完成后返回为true;
            if (pool.isTerminated()) {
                try {
                    System.out.println("確認---ing");
                    Thread.sleep(9000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                break;
            }
        }

    }