TestThread.java
package com.example.thread;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
int all2 = test2();
System.out.println("用时:" + (System.currentTimeMillis() - start));
System.out.println("all2的值为:" + all2);
}
private static int test2() throws InterruptedException, ExecutionException {
ExecutorService service = Executors.newFixedThreadPool(10);
ArrayList<Future<Integer>> list = new ArrayList<>();
for (int i = 0; i < 20; i++) {
CallableTest callableTest = new CallableTest(i);
list.add(service.submit(callableTest));
}
int all = 0;
for (Future<Integer> dateFuture : list) {
all = all + dateFuture.get();
}
return all;
}
}
CallableTest.java
package com.example.thread;
import java.util.concurrent.Callable;
public class CallableTest implements Callable<Integer> {
private int num;
public CallableTest(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
Thread.sleep(500);
return num;
}
}
参考文章