线程安全的集合类
主要介绍HashTable,ConcurrentHashMap,CopyOnWriteArrayList,CopyOnWriteArraySet,Vector,常用的StringBuffer与StringBuild。
由于线程安全的集合类用法都比较简单,所以下面更多是看看源码。
Vector
/**
* 多线程使用Vector或者HashTable的示例(简单线程同步问题) 线程安全的容器
*/
public class Tickets {
public static void main(String[] args) {
// 初始化火车票池并添加火车票:避免线程同步可采用Vector替代ArrayList HashTable替代HashMap
Vector<String> tickets = new Vector<String>();
for (int i = 1; i <= 1000; i++) {
tickets.add("火车票" + i);
}
for (int i = 1; i <= 10; i++) {
new Thread("线程" + i) {
public void run() {
while (true) {
if (tickets.isEmpty())
break;
System.out.println(Thread.currentThread().getName() + "---" + tickets.remove(0));
}
}
}.start();
}
}
}
可以看到在jdk源码中vector许多方法都是用synchornized修饰的。
HashTable
/**
* @classDesc: 演hashtable用法
* @author: hj
* @date:2018年12月12日 下午8:36:43
*/
public class UserHashTable {
public static void main(String[] args) {
Hashtable<String, Integer> number = new Hashtable<String, Integer>();
number.put("1", 1);
number.put("2", 2);
number.put("3", 3);
number.put("4", 4);
Integer n = number.get("1");
if (n != null) {
System.out.println("1= " + n);
}
}
}
CopyOnWriteArray
/**
* @classDesc: copyOnWrite
* @author: hj
* @date:2018年12月12日 下午8:44:34
*/
public class UseCopyOnWrite {
public static void main(String[] args) {
CopyOnWriteArrayList<String> cwal = new CopyOnWriteArrayList<String>();
CopyOnWriteArraySet<String> cwas = new CopyOnWriteArraySet<String>();
cwal.add("");
}
}
ConcurrentMap
/**
* @classDesc: 演示ConcurrentMap
* @author: hj
* @date:2018年12月12日 下午8:45:43
*/
public class UseConcurrentMap {
public static void main(String[] args) {
ConcurrentHashMap<String, Object> chm = new ConcurrentHashMap<String, Object>();
chm.put("k1", "v1");
chm.put("k2", "v2");
chm.put("k3", "v3");
chm.putIfAbsent("k4", "v4");
System.out.println(chm.get("k3"));
System.out.println(chm.size());
for (Map.Entry<String, Object> me : chm.entrySet()) {
System.out.println(me.getKey() + me.getValue());
}
}
}
对于stringBuffer与stringbuilder而言,只要记得stringBuffer是线程安全的,stringbuilder是线程不安全的。