ConcurrentHashMap 介绍
- computeIfAbsent(key,Function):
- 如果存在则返回key的值
- 如果不存在,则Function返回值作为key的值
- merge(key,value,BiFunction):
- 不存在指定的key时,将value设置为key的值。
- 当key存在值时,执行BiFunction接收oldKey和value,返回结果设置为key的值。
实验介绍
- 将26个英文字母分别循环200次,每个字母作为一个单词,一共有5200个单词。
- 每个单词中间用"\n"分隔,乱序存入26个文件中
- 生成26个线程对26个文件中的单词进行计数,存入map中
环境搭建
生成文件
@Test
public void produceData() throws IOException {
String data="abcdefghijklmnopqrstuvwxyz";
List<String> list=new ArrayList<>();
for (int i = 0; i < data.length(); i++) {
for (int j = 0; j < 200; j++) {
list.add(String.valueOf(data.charAt(i)));
}
}
Collections.shuffle(list);
for (int i = 0; i < 26; i++) {
try(FileWriter fw=new FileWriter((i+1)+".txt")){
fw.write(list.subList(i*200,(i+1)*200).stream().collect(Collectors.joining("\n")));
}
}
}
读取文件
private static void read(List list,int i){
try(BufferedReader bf=new BufferedReader(new FileReader((i+1)+".txt")) ){
String data;
while((data=bf.readLine())!=null){
list.add(data);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
生成线程:操作每个文件对应的list,存放到线程共享的map
private static <T>void deal(Supplier<Map<String,T>> supplier, BiConsumer<Map<String,T>,List<String>> consumer){
Map<String,T> map=supplier.get();
CountDownLatch count=new CountDownLatch(26);
for (int i = 0; i < 26; i++) {
int j=i;
new Thread(()->{
List<String> list=new ArrayList();
read(list,j);
consumer.accept(map,list);
count.countDown();
}).start();
}
try {
count.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
Collection<T> values = map.values();
System.out.println(values.toString());
}
测试
代码
public static void main(String[] args) {
deal(()-> new ConcurrentHashMap<String, LongAdder>(),(map, list)->{
list.forEach(str->{
map.computeIfAbsent(str,(key)-> new LongAdder()).increment();
});
});
deal(()-> new ConcurrentHashMap<String, Integer>(),(map, list)->{
list.forEach(str->{
map.merge(str,1,Integer::sum);
});
});
}
输出
[200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]