import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class findProduct {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Map<Integer, List<String>> map = new HashMap<>();
long startTime=System.nanoTime();
List<Future<List<String>>> futureList = new ArrayList<>();
ExecutorService service = Executors.newFixedThreadPool(10);
for(int i=0;i<1000;i++){
futureList.add(service.submit(new Products(i,i*2)));
}
service.shutdown();
while (true) {
if (service.isTerminated()) {
int m = 0;
for (Future<List<String>> future : futureList) {
if (null != future.get()) {
m += 1;
List<String> result = future.get();
map.put(m,result);
}
}
break;
}
Thread.sleep(50);
}
long endTime=System.nanoTime(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ns");
System.out.println(map);
}
static class Products implements Callable<List<String>>{
private Integer key;
private int value;
public Products(Integer key, int value){
this.key = key;
this.value = value;
}
@Override
public List<String> call() throws Exception {
List<String> list = new ArrayList<>();
if (key % 10 == 0){
Thread.currentThread().sleep(100);
}
String product = "分片:" + key + "产品" + value;
list.add(product);
return list;
}
}
}