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));
}
输出:
当前时间1:1558513799576
当前花费时间2: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-5
当前花费时间3:2290
当我们使用第二种方式的时候:
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));
}
输出:
当前时间1: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-5
当前花费时间:10024
由于Future.get()方法是阻塞的,所以,我们在使用有返回值的线程池时,不能在每次提交任务后立即调用于Future.get()方法。使用第一种方法是最好的