package com.github.pig.auth; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.Vector; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class Test { private List<String> tikets1 = new ArrayList<>(); private Queue<String> tikets2 = new ConcurrentLinkedQueue<>(); Test() { for (int i = 0; i < 100000; i++) { tikets1.add("票编号" + i); } for (int i = 0; i < 100000; i++) { tikets2.add("票编号" + i); } } private static StringBuffer sb = new StringBuffer(); public void aa() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (this) { while (tikets1.size() > 0) { sb.append("销售了--" + tikets1.remove(0) + "\n"); } } } public void bb() { try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } while (true) { String s = tikets2.poll(); if (s == null) { break; } else { sb.append("销售了--" + s + "\n"); } } } CountDownLatch latch = new CountDownLatch(10); public static void main(String[] args) { Test t = new Test(); long start = 0L; List<Thread> lists = new ArrayList<>(); for (int i = 0; i < 10; i++) { // Thread th = new Thread(t::aa); Thread th = new Thread(t::bb); th.start(); lists.add(th); if (i == 9) { start = System.currentTimeMillis(); } t.latch.countDown();//等待所有线程一起开始 } //等待所有线程结束 lists.forEach(o -> { try { o.join(); } catch (InterruptedException e) { e.printStackTrace(); } }); long end = System.currentTimeMillis(); System.out.println(sb.toString()); System.out.println(end - start + "ms"); } }
用队列效率最高 ,30ms
如果用synchronized要1000多ms