本文共 5466 字,大约阅读时间需要 18 分钟。
public class Constants { public static final int COUNT = 1000000; public static final int THREAD_COUNT = 100;}
public class T01_TestHashtable { static Hashtablem = new Hashtable<>(); static int count = Constants.COUNT; static UUID[] keys = new UUID[count]; static UUID[] values = new UUID[count]; static final int THREAD_COUNT = Constants.THREAD_COUNT; static { for (int i = 0; i < count; i++) { keys[i] = UUID.randomUUID(); values[i] = UUID.randomUUID(); } } static class MyThread extends Thread { int start; int gap = count/THREAD_COUNT; public MyThread(int start) { this.start = start; } @Override public void run() { for(int i=start; i { for (int j = 0; j < 10000000; j++) { m.get(keys[10]); } }); } for(Thread t : threads) { t.start(); } for(Thread t : threads) { try { t.join(); } catch (InterruptedException e) { e.printStackTrace(); } } end = System.currentTimeMillis(); System.out.println(end - start); }}
相对来说,插入的时候ConcurrentHashMap相对于HashMap效率没有明显提高,但是读取的时候效率高很多。
public boolean add(E e) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }
public E get(int index) { return get(getArray(), index); }
static BlockingQueuetasks = new DelayQueue<>(); static Random r = new Random(); 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(this.getDelay(TimeUnit.MILLISECONDS) < o.getDelay(TimeUnit.MILLISECONDS)) return -1; else if(this.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; } }
main方法:
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()); } }
结果:
t5 1587472415617t1 1587472416117t3 1587472416617t2 1587472417117t4 1587472417617
public class T07_01_PriorityQueque { public static void main(String[] args) { PriorityQueueq = 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/