您的位置:首页 > 编程语言 > Java开发

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

2015-06-21 11:04 495 查看
一、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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: