1.对于线程安全的最好办法是map不可变,从而天然的支持了线程安全;
2.需要在项目构建中导入guava包,以及在需要使用的模块中导入guava;
3.使用:
package com.ydlclass.collection;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMultimap;
public class GuavaTest {
public static void main(String[] args) {
String[] strings = {"a","b","c"};
ImmutableList<String> list = ImmutableList.copyOf(strings);//静态方法,拷贝完成之后就变成不可变的一个数据,就不能使用add方法
for (String s : list) {
System.out.println(s);//不可变类型天然是线程安全的,可以用于遍历但是不能用于修改;
}
ImmutableMultimap<String,Integer> multimap = ImmutableMultimap.of("a",1,"b",2);//同样可以遍历操作
for (String str : multimap.keys()){
System.out.println(str + " = " + multimap.get(str) );
}
}
}
//结果:
/***
* a
* b
* c
* a = [1]
* b = [2]
*/