有返回值的线程池

335 阅读1分钟
public static void main(String[] args) {
    List<Future> futureList = new ArrayList<>();
        long time1 = System.currentTimeMillis();
        System.out.println("当前时间1:" + time1);
        for (int i = 0; i < 10; i++) {
            Future future = executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
            futureList.add(future);
        }

        long time2 = System.currentTimeMillis();
        System.out.println("当前花费时间2:" + (time2 - time1));
        for (Future future : futureList) {
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        long time3 = System.currentTimeMillis();
        System.out.println("当前花费时间3:" + (time3 - time2));
}

输出:

当前时间11558513799576
当前花费时间26
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
当前花费时间32290

当我们使用第二种方式的时候:

public static void main(String[] args) {
    long time1 = System.currentTimeMillis();
        System.out.println("当前时间1:" + time1);
        for (int i = 0; i < 10; i++) {
            Future future = executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            });
            try {
                future.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
        long time2 = System.currentTimeMillis();
        System.out.println("当前花费时间:" + (time2 - time1));
}

输出:

当前时间11558514825490
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
pool-1-thread-1
pool-1-thread-2
pool-1-thread-3
pool-1-thread-4
pool-1-thread-5
当前花费时间:10024

由于Future.get()方法是阻塞的,所以,我们在使用有返回值的线程池时,不能在每次提交任务后立即调用于Future.get()方法。使用第一种方法是最好的