水滴石穿--多线程安全的集合

线程安全的集合类

主要介绍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是线程不安全的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值