本文共 3585 字,大约阅读时间需要 11 分钟。
Queue(队列)和Deque(双端队列)是处理高并发场景的核心容器。Deque比普通的队列更灵活,支持从任一端添加和移除元素,常见用途是线程安全的生产者-消费者模型。
Hashtable在早期JDK版本中因加锁导致性能瓶颈,后续开发者通过ConcurrentHashtable优化,但其性能仍不如现代的ConcurrentHashMap。通过本地测试发现,ConcurrentHashMap在插入操作上与Hashtable效率无明显差异,但在读取时效率显著提升。
public class T01_TestHashtable { static final int COUNT = 1000000; static final int THREAD_COUNT = 100; public static void main(String[] args) throws InterruptedException { long start = System.currentTimeMillis(); final MyThread[] threads = new MyThread[THREAD_COUNT]; for (int i = 0; i < threads.length; i++) { threads[i] = new MyThread(i * (COUNT / THREAD_COUNT)); } for (MyThread t : threads) { t.start(); } for (MyThread t : threads) { t.join(); } long end = System.currentTimeMillis(); System.out.println(end - start); System.out.println(m.size()); } static Hashtable m = new Hashtable<>(); static class MyThread extends Thread { int start; int gap = COUNT / THREAD_COUNT; MyThread(int start) { this.start = start; } @Override public void run() { for (int i = start; i < start + gap; i++) { m.put(keys[i], values[i]); } } }} ConcurrentSkipListMap采用跳表结构,通过CAS算法实现并发安全。其底层是基于链表的结构,通过跳跃查找减少了树操作的复杂性,显著提升了查找效率。
优先使用Queue
CopyOnWrite机制
BlockingQueue的多样实现
PriorityQueue:基于小顶堆的优先队列,适合任务调度。
static BlockingQueuetasks = new DelayQueue<>();static class MyTask implements Delayed { String name; long runningTime; MyTask(String name, long rt) { this.name = name; this.runningTime = rt; } @Override public int compareTo(Delayed o) { if (getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) { return -1; } else if (getDelay(TimeUnit.MILLISECONDS) > o.getDelay(TimeUnit.MILLISECONDS)) { return 1; } else { return 0; } } @Override public long getDelay(TimeUnit unit) { return unit.convert(runningTime - System.currentTimeMillis(), TimeUnit.MILLISECONDS); } @Override public String toString() { return name + " " + runningTime; }}public static void main(String[] args) throws InterruptedException { long now = System.currentTimeMillis(); MyTask t1 = new MyTask("t1", now + 1000); MyTask t2 = new MyTask("t2", now + 2000); MyTask t3 = new MyTask("t3", now + 1500); MyTask t4 = new MyTask("t4", now + 2500); MyTask t5 = new MyTask("t5", now + 500); tasks.put(t1); tasks.put(t2); tasks.put(t3); tasks.put(t4); tasks.put(t5); System.out.println(tasks); for (int i = 0; i < 5; i++) { System.out.println(tasks.take()); }}
public class T07_01_PriorityQueque { public static void main(String[] args) { PriorityQueue q = new PriorityQueue<>(); q.add("c"); q.add("e"); q.add("a"); q.add("d"); q.add("z"); for (int i = 0; i < 5; i++) { System.out.println(q.poll()); } }} 输出结果:a、c、d、e、z
转载地址:http://ydlzz.baihongyu.com/