JUnit4 測試多線程

JUnit4 實際上不支持測試多線程程序。

The article at http://www.planetgeek.ch/2009/08/25/how-to-find-a-concurrency-bug-with-java/describes a method of exposing concurrency bugs that adds a new assertion method assertConcurrent.

該文章中提供了一個新的斷言方法來測試多線程程序:
assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds)

  • final String message:如果測試不通過,打印出的消息
  • final List<? extends Runnable> runnables:需要測試的線程
  • final int maxTimeoutSeconds:最長運行時間,單位 秒,如果超時,則測試不通過

該方法將需要測試的線程放入一個線程池中,并發(fā)執(zhí)行,最后判斷是否有異常發(fā)生,是否有超時發(fā)生。

示例如下:
如下的代碼會產(chǎn)生超時,測試不通過。
java.lang.AssertionError: Test Failed timeout! More than1seconds

public class JUnit4_Test {
    @Test
    public void test1() throws Exception {
        List<Runnable> runnables = new ArrayList<>(10);
        for (int i = 0; i < 10; i++) {
            runnables.add(new MyRunnable());
        }

        assertConcurrent("Test Failed", runnables, 1);
    }

    public static void assertConcurrent(final String message, final List<? extends Runnable> runnables, final int maxTimeoutSeconds) throws InterruptedException {
        final int numThreads = runnables.size();
        final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
        final ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
        try {
            final CountDownLatch allExecutorThreadsReady = new CountDownLatch(numThreads);
            final CountDownLatch afterInitBlocker = new CountDownLatch(1);
            final CountDownLatch allDone = new CountDownLatch(numThreads);
            for (final Runnable submittedTestRunnable : runnables) {
                threadPool.submit(new Runnable() {
                    public void run() {
                        allExecutorThreadsReady.countDown();
                        try {
                            afterInitBlocker.await();
                            submittedTestRunnable.run();
                        } catch (final Throwable e) {
                            exceptions.add(e);
                        } finally {
                            allDone.countDown();
                        }
                    }
                });
            }
            // wait until all threads are ready
            assertTrue("Timeout initializing threads! Perform long lasting initializations before passing runnables to assertConcurrent", allExecutorThreadsReady.await(runnables.size() * 10, TimeUnit.MILLISECONDS));
            // start all test runners
            afterInitBlocker.countDown();
            assertTrue(message + " timeout! More than" + maxTimeoutSeconds + "seconds", allDone.await(maxTimeoutSeconds, TimeUnit.SECONDS));
        } finally {
            threadPool.shutdownNow();
        }
        assertTrue(message + "failed with exception(s)" + exceptions, exceptions.isEmpty());
    }
}

class MyRunnable implements Runnable {
    public void run() {
        try {
            Thread.sleep(10000);
        } catch (Exception e) {
        } finally {

        }
    }
}

引用:
Multithreaded code and concurrency

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,506評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,625評論 18 399
  • 對象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構(gòu)造函數(shù)創(chuàng)建對象:僅僅是創(chuàng)建對象的方法,并非Fa...
    孫小磊閱讀 2,177評論 0 3
  • 文 / 戒閑 何靜最近很煩,她一直隨身攜帶的那塊懷表不走了,跑了很多地方都沒辦法修好。 木木早就看出來了她的焦躁不...
    花一堯閱讀 513評論 0 1
  • 劉世超 文魁大腦90天學(xué)習(xí)計劃 第10天 1.5 今日學(xué)習(xí):無 今日訓(xùn)練: 讀數(shù)訓(xùn)練20分鐘: 平均用時33s左右...
    24K超超老師閱讀 420評論 0 0

友情鏈接更多精彩內(nèi)容