1. TestCallable 类继承 Callable
class TestCallable implements Callable {
private List<Integer> list;
public TestCallable(List<Integer> list) {
this.list = list;
}
/**
* Computes a result, or throws an exception if unable to do so.
*
* @return computed result
* @throws Exception if unable to compute a result
*/
@Override
public Object call() throws Exception {
List<Integer> collect = list.stream().map(f -> {
System.out.println(Thread.currentThread().getName() + "------------" + Thread.currentThread().getId());
//加随机数才能体现出来,加固定的 还不如单线程。
return f + RandomUtils.nextInt(0,2000);
}).collect(Collectors.toList());
return collect;
}
}
2.创建 ThreadTest 类
public class ThreadTest {
// private static ExecutorService executor = Executors.newFixedThreadPool(20);
// 创建线程池
private static ThreadPoolExecutor executor = new ThreadPoolExecutor(20,
200, 10, TimeUnit.SECONDS,
new LinkedBlockingDeque<>(10000),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) throws ExecutionException, InterruptedException {
//创建模拟数据
List<Integer> list1 = new ArrayList();
for (int i = 0; i < 1000000; i++) {
list1.add(i);
}
long start = System.currentTimeMillis();
//这个是普通提交的
// List<Integer> collect = list1.stream().map(f -> {
// System.out.println(Thread.currentThread().getName()+"------------"+Thread.currentThread().getId());
// return f + RandomUtils.nextInt(0,2000);
// }).collect(Collectors.toList());
int size = 100000;
//判断一下分几段,用几个线程进行操作
int test = size % 10000 == 0 ? size / 10000 : size / 10000 + 1;
List<Future<?>> results = new LinkedList<Future<?>>();
for (int j = 0; j < test; j++) {
int end = (j + 1) * 10000;
if (end > size) {
end = size;
}
List<Integer> subList = list1.subList(j * 10000, end);
TestCallable callable = new TestCallable(subList);
FutureTask futureTask=new FutureTask(callable);
executor.submit(futureTask);
//添加的是 FutureTask 不是 submit返回的Future 那个get 获取不到。
results.add(futureTask);
}
executor.shutdown();
while (true) {
if (executor.isTerminated()) {
break;
}
}
for (Future<?> future:results){
System.out.println(future.get());
}
long date = System.currentTimeMillis() - start;
System.out.println("======" + date + "======");
}