public static void main(String[] args) {
    List<Future> futureList = new ArrayList<>();
        long time1 = System.currentTimeMillis();
        System.out.println("Current time 1:" + time1);
        for (int i = 0; i < 10; i++) {
            Future future = executorService.submit(new Runnable() {
                @Override
                public void run(a) {
                    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("Current time spent 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("Current time spent 3:" + (time3 - time2));
}
Copy the code

Output:

The current time1:1558513799576Current time spent2:6
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-5Current time spent3:2290

Copy the code

When we use the second method:

public static void main(String[] args) {
    long time1 = System.currentTimeMillis();
        System.out.println("Current time 1:" + time1);
        for (int i = 0; i < 10; i++) {
            Future future = executorService.submit(new Runnable() {
                @Override
                public void run(a) {
                    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("Current time spent:" + (time2 - time1));
}
Copy the code

Output:

The current time1:1558514825490
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-5Current time spent:10024
Copy the code

Because the future.get () method is blocked, we cannot call the future.get () method immediately after each submission when we use a thread pool with a return value. Using the first method is the best