1. 程式人生 > >一個測試任務併發執行時間的方法

一個測試任務併發執行時間的方法

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;

/**
 * Created by xuyizhen on 2017/4/16.
 */
public class Util {
    /**
     * 測試任務task在指定的執行緒池execurtor中的併發度與效能的關係
     * 注意:執行緒池中的執行緒數必須不小於併發度,否則將導致執行緒飢餓死鎖
     *
     * @param executor
     * @param concurrency
     * @param task
     * @return
     */
    public static long timeTest(Executor executor, int concurrency, final Runnable task) throws InterruptedException {
        final CountDownLatch allReady = new CountDownLatch(concurrency);
        final CountDownLatch start = new CountDownLatch(1);
        final CountDownLatch allOver = new CountDownLatch(concurrency);

        for (int i = 0; i < concurrency; i++) {
            executor.execute(new Runnable() {
                public void run() {
                    allReady.countDown();
                    try {
                        start.await();
                        task.run();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        Thread.currentThread().interrupt();//使該斷言能被Executor感知到
                    } finally {
                        allOver.countDown();
                    }
                }
            });
        }
        allReady.await();
        long startTime = System.nanoTime();
        start.countDown();
        allOver.await();
        long endTime = System.nanoTime();
        return endTime - startTime;
        //對於這種測試時間間隔的定時,要使用nanoTime而非currentTimeMills。因為前者更加準確並且不受實時時鐘的影響。
    }
}