@Test public void testPaceController_multiThread() throws InterruptedException { final PaceController paceController = new PaceController(1000, 160d); final Node node = mock(Node.class); final AtomicInteger passcount = new AtomicInteger(); final AtomicInteger blockcount = new AtomicInteger(); final AtomicInteger done = new AtomicInteger(); AtomicLong lastTm = new AtomicLong(System.currentTimeMillis() / 1000); int count = 1000; final CountDownLatch countDown = new CountDownLatch(count); for (int i = 0; i < count; i++) { Thread thread = new Thread(new Runnable() { @Override public void run() { for(int j =0; j< 10; j++) { boolean pass = paceController.canPass(node, 1).isPass(); if (pass == true) { passcount.incrementAndGet(); } else { blockcount.incrementAndGet(); } done.incrementAndGet(); long now = System.currentTimeMillis() / 1000; if (lastTm.get() != now) { System.out.println("pass:" + passcount.get() + ", tm:" + lastTm.get()); System.out.println("block:" + blockcount.get() + ", tm:" + lastTm.get()); System.out.println("done:" + done.get() + ", tm:" + lastTm.get()); passcount.set(0); blockcount.set(0); done.set(0); } lastTm.set(now); } countDown.countDown(); } }, "Thread " + i); thread.start(); } countDown.await(); System.out.println("pass:" + passcount.get() + ", tm:" + lastTm.get()); System.out.println("block:" + blockcount.get() + ", tm:" + lastTm.get()); System.out.println("done:" + done.get() + ", tm:" + lastTm.get()); }
一段JAVA代码了解多线程,JUC、CAS原子性操作。
内容版权声明:除非注明,否则皆为本站原创文章。