使用闭锁,直接上代码。
public class Benchmark { private static final int THREADS_NUM = 2; private static void runWork() { long start = System.currentTimeMillis(); for (int i = 0; i < 100000; i++) { long tmp = new Random().nextLong() * new Random().nextLong() / new Random().nextLong(); } System.out.println(Thread.currentThread().getName() + " cost : " + (System.currentTimeMillis() - start) + " ms"); } @Test public void bench() throws Exception { Thread[] threads = new Thread[THREADS_NUM]; CountDownLatch latch = new CountDownLatch(THREADS_NUM); for (int i = 0; i < THREADS_NUM; i++) { threads[i] = new Thread(new Runnable() { @Override public void run() { try { runWork(); } catch (Exception e) { } finally { // 任务完成后 latch.countDown(); } } }, "Worker-" + i); threads[i].start(); } latch.await(); System.out.println("Test Finish."); } } |
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。