package com.zhangxueliang.demo.springbootdemo.JUC.c_026_01_ThreadPool;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
/**
* @ProjectName springbootdemo_src
* @ClassName T09_FixedThreadPool
* @Desicription TODO
* @Author Zhang Xueliang
* @Date 2019/12/5 19:55
* @Version 1.0
**/
public class T09_FixedThreadPool {
public static void main(String[] args) throws ExecutionException, InterruptedException {
long start,end;
start=System.currentTimeMillis();
//第一种方式
// List<Integer> integers = getPrime(1, 200000);//一共耗时: 2156
//第二种方式
ExecutorService executorService = Executors.newFixedThreadPool(4);//一共耗时: 1104
Task task1 = new Task(1, 50000);
Task task2 = new Task(50001, 100000);
Task task3 = new Task(100001, 150000);
Task task4 = new Task(150001, 200000);
/*Future<List<Integer>> future1 = executorService.submit(task1);
Future<List<Integer>> future2 = executorService.submit(task2);
Future<List<Integer>> future3 = executorService.submit(task3);
Future<List<Integer>> future4 = executorService.submit(task4);
List<Integer> list1 = future1.get();
List<Integer> list2 = future2.get();
List<Integer> list3 = future3.get();
List<Integer> list4 = future4.get();*/
//第三种方式
CompletableFuture<List<Integer>> c1 = CompletableFuture.supplyAsync(() -> getPrime(1, 50000));//一共耗时: 1269
CompletableFuture<List<Integer>> c2 = CompletableFuture.supplyAsync(() -> getPrime(50001, 100000));
CompletableFuture<List<Integer>> c3 = CompletableFuture.supplyAsync(() -> getPrime(100001, 150000));
CompletableFuture<List<Integer>> c4 = CompletableFuture.supplyAsync(() -> getPrime(150001, 200000));
List<Integer> list1 = c1.get();
List<Integer> list2 = c2.get();
List<Integer> list3 = c3.get();
List<Integer> list4 = c4.get();
end=System.currentTimeMillis();
System.out.printf("一共耗时: %s",end-start);
executorService.shutdown();
}
static class Task implements Callable<List<Integer>> {
int start,end;
public Task(int start, int end) {
this.start = start;
this.end = end;
}
@Override
public List<Integer> call() throws Exception {
return getPrime(start,end);
}
}
private static List<Integer> getPrime(int start, int end) {
List<Integer> results = new ArrayList<>();
for (int j = start; j <end ; j++) {
if (isPrime(j)) results.add(j);
}
return results;
}
private static boolean isPrime(int num) {
for (int i = 2; i <num/2 ; i++) {
if (num%i==0) return false;
}
return true;
}
}