import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;
public class MapParallelTraversal {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
// 填充数据到Map中
for (int i = 0; i < 1000000; i++) {
map.put(i, String.valueOf(i));
}
// 并行遍历Map
long startTime = System.nanoTime();
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new MapTraversalTask(map));
long endTime = System.nanoTime();
System.out.println("Parallel traversal time: " + (endTime - startTime) / 1000000 + " ms");
}
}
class MapTraversalTask extends RecursiveAction {
private final Map<Integer, String> map;
private static final int THRESHOLD = 1000;
public MapTraversalTask(Map<Integer, String> map) {
this.map = map;
}
@Override
protected void compute() {
if (map.size() > THRESHOLD) {
invokeAll(splitMap(map));
} else {
for (Map.Entry<Integer, String> entry : map.entrySet()) {
// 处理每个键值对
System.out.println(entry.getKey());
}
}
}
private List<MapTraversalTask> splitMap(Map<Integer, String> map) {
List<MapTraversalTask> tasks = new ArrayList<>();
int splitSize = map.size() / THRESHOLD;
for (int i = 0; i < splitSize; i++) {
Map<Integer, String> subMap = new HashMap<>();
map.entrySet().stream() // 方法返回Map中的所有条目(键-值对)作为一个Set视图。
.skip(i * THRESHOLD) //这个操作跳过前i * THRESHOLD个条目。
.limit(THRESHOLD) //这个操作限制Stream中的条目数量为THRESHOLD
.forEach(entry -> subMap.put(entry.getKey(), entry.getValue())); //Stream中的每一个条目(键-值对),都将其放入subMap中。
tasks.add(new MapTraversalTask(subMap));
}
return tasks;
}
}
ForkJoinPool pool = new ForkJoinPool(); 用来实现并行的实例