Java并发编程-33-线程安全的可遍历映射

一、ConcurrentNavigableMap

这个接口的类用一下两个部分存放元素

  • 一个键值,他是元素的唯一标识
  • 元素的其他部分数据

二、ConcurrentSkipListMap

这个类内部使用了Skip List来存放数据,Skip List是基于并发列表的数据结构,效率与二叉树相近

参考这里

三、测试

package com.concurrencycollection;

/**
 * 实体类,保存的是联系人信息
 * @author Nicholas
 *
 */
public class Contact {

	private String name;
	private String phone;

	public Contact(String name, String phone) {
		this.name = name;
		this.phone = phone;
	}

	public String getName() {
		return name;
	}

	public String getPhone() {
		return phone;
	}

	@Override
	public String toString() {
		return "Contact [name=" + name + ", phone=" + phone + "]";
	}
	
}

package com.concurrencycollection;

import java.util.concurrent.ConcurrentSkipListMap;

public class Task implements Runnable {

	private ConcurrentSkipListMap<String, Contact> concurrentSkipListMap;

	private String id;

	public Task(ConcurrentSkipListMap<String, Contact> concurrentSkipListMap,
			String id) {
		this.concurrentSkipListMap = concurrentSkipListMap;
		this.id = id;
	}

	@Override
	public void run() {
		for (int i = 0; i < 1000; i++) {
			Contact contact = new Contact(id, String.valueOf(i + 1000));
			concurrentSkipListMap.put(id + contact.getPhone(), contact);
		}
	}

}

	public void testContact() {
		ConcurrentSkipListMap<String, Contact> concurrentSkipListMap = new ConcurrentSkipListMap<String, Contact>();
		Thread[] threads = new Thread[25];
		int counter = 0;
		for (char i = 'A'; i < 'Z'; i++) {
			Task task = new Task(concurrentSkipListMap, String.valueOf(i));
			threads[counter] = new Thread(task);
			threads[counter].start();
			counter++;
		}

		for (int i = 0; i < threads.length; i++) {
			try {
				threads[i].join();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		System.out.println("Main : Size of the map "
				+ concurrentSkipListMap.size());

		Map.Entry<String, Contact> elementEntry;

		Contact contact;

		elementEntry = concurrentSkipListMap.firstEntry();

		contact = elementEntry.getValue();

		System.out.println("Main : First Entry :" + contact);

		elementEntry = concurrentSkipListMap.lastEntry();

		contact = elementEntry.getValue();

		System.out.println("Main : Last Entry :" + contact);

		// 取得子映射

		System.out.println("Main : submap from A1996 to B1002:");

		ConcurrentNavigableMap<String, Contact> subMap = concurrentSkipListMap
				.subMap("A1996", "B1002");

		do {
			elementEntry = subMap.pollFirstEntry();
			if (elementEntry != null) {
				contact = elementEntry.getValue();
				System.out.println("Contact : " + contact);
			}
		} while (elementEntry != null);
	}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值