Vector输出结果不是5000的问题
来源:5-6 同步容器-1
![](http://img1.sycdn.imooc.com/user/53a862ee0001909301800180-100-100.jpg)
互联网的搬运工
2018-03-24
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); }
输出结果:
11:41:57.559 [main] INFO com.okali.concurrency.commonUnsafe.HashMapExample - size:4989
写回答
3回答
-
latch.countDown(); 位置错了~052018-08-22
-
贰零一贰
2018-12-31
我和楼主的问题一样,“countDownLatch.countDown();”的位置不对,写成下面这样就好了:
public static void main(String[] args) throws InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); final Semaphore semaphore = new Semaphore(threadTotal); final CountDownLatch countDownLatch = new CountDownLatch(clientTotal); for (int i = 0; i < clientTotal; i++){ final int count = i; executorService.execute(() -> { try { semaphore.acquire(); add(count); semaphore.release(); } catch (InterruptedException e) { log.error("exception", e); } countDownLatch.countDown(); }); } countDownLatch.await(); executorService.shutdown(); log.info("size:{}", list.size()); }
10 -
Jimin
2018-03-24
你好,你运行的结果不是这个例子的。。。。是 HashMapExample 例子的
00
相似问题