目录
ConcurrentSkipListMap
SkipList是一个基于并行列表的数据结构,其性能可以比拟二叉树。关于SkipList。
- subMap(K fromKey,K toKey):返回从fromKey元素到toKey元素的子集。
- headMap(K toKey):返回从首个元素到小于toKey的元素的子集。
- tailMap(K fromKey):返回从fromKey值元素到结尾元素的子集。
- putIfAbsent(K key,V value):key不存在,则进行put。
- pollFirstEntry/pollLastEntry():返回并移除首个/末尾的Map.Entry对象元素。
一、主程序
package xyz.jangle.thread.test.n7_6.concurrentskiplistmap;
import java.util.Map;
import java.util.concurrent.ConcurrentNavigableMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* 7.5、线程安全的navigable map
* ConcurrentSkipListMap DEMO
*
* @author jangle
* @email jangle@jangle.xyz
* @time 2020年9月14日 下午4:59:55
*
*/
public class M {
public static void main(String[] args) {
var map = new ConcurrentSkipListMap<String, Contact>();
var threads = new Thread[26];
int counter = 0;
for (char i = 'A'; i <= 'Z'; i++) {
var task = new Task(map, String.valueOf(i));
threads[counter] = new Thread(task);
threads[counter].start();
counter++;
}
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("M:map Size:" + map.size());
Map.Entry<String, Contact> element;
Contact contact;
// 获取第一个元素
element = map.firstEntry();
contact = element.getValue();
System.out.println("M: 第一个元素:" + contact.getName() + "," + contact.getPhone());
System.out.println("M: 获取子集A1991 到B1001");
// 获取子集
ConcurrentNavigableMap<String, Contact> subMap = map.subMap("A1991", "B1001");
do {
element = subMap.pollFirstEntry();
if (element != null) {
contact = element.getValue();
System.out.println(contact.getName() + ":" + contact.getPhone());
}
} while (element != null);
}
}
二、联系人
package xyz.jangle.thread.test.n7_6.concurrentskiplistmap;
/**
* 联系人类
* @author jangle
* @email jangle@jangle.xyz
* @time 2020年9月14日 下午5:02:53
*
*/
public class Contact {
private final String name;
private final String phone;
public Contact(String name, String phone) {
super();
this.name = name;
this.phone = phone;
}
public String getName() {
return name;
}
public String getPhone() {
return phone;
}
}
三、任务类
package xyz.jangle.thread.test.n7_6.concurrentskiplistmap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* 任务类(为ConcurrentSkipListMap添加元素)
* @author jangle
* @email jangle@jangle.xyz
* @time 2020年9月14日 下午5:04:09
*
*/
public class Task implements Runnable {
private final ConcurrentSkipListMap<String, Contact> map;
private final String id;
public Task(ConcurrentSkipListMap<String, Contact> map, String id) {
super();
this.map = map;
this.id = id;
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
var contact = new Contact(id, String.valueOf(i + 1000));
map.put(id + contact.getPhone(), contact);
}
}
}
四、执行结果
M:map Size:26000
M: 第一个元素:A,1000
M: 获取子集A1991 到B1001
A:1991
A:1992
A:1993
A:1994
A:1995
A:1996
A:1997
A:1998
A:1999
B:1000