1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | public class VectorExample { // 请求总数 public static int clientTotal = 5000 ; // 并发数 public static int threadTotal = 200 ; private static Vector<Integer> vector = new Vector<>(); public static void main(String[] args) throws InterruptedException { ExecutorService exec = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threadTotal); final CountDownLatch latch = new CountDownLatch(clientTotal); for ( int i = 0 ; i < clientTotal; i++) { final int count = i; exec.execute( new Runnable() { @Override public void run() { try { semaphore.acquire(); update(count); semaphore.release(); } catch (InterruptedException e) { log.error( "exception" , e); } } }); latch.countDown(); // 每一个请求减一 } latch.await(); // latch为0的时候输出结果 exec.shutdown(); log.info( "size:{}" ,vector.size()); } private static void update ( int i) { vector.add(i); } |
输出结果:
1 | 11 : 41 : 57.559 [main] INFO com.okali.concurrency.commonUnsafe.HashMapExample - size: 4989 |