【问题标题】:When executor meets Thread.sleep, why the thread ends without sleeping or throw InterruptedException?当executor遇到Thread.sleep,为什么线程不休眠就结束或者抛出InterruptedException?
【发布时间】:2016-09-27 06:02:16
【问题描述】:

不知道junit为什么会有以下行为:

当我将一个线程提交给执行器(fixedThreadPool 或其他),而该线程具有睡眠行为(Thread.sleep())时,我发现该线程立即结束!没有睡眠,没有中断的Excetion。

不知道为什么?

(我知道下面的设计不好,但我只是想描述一下上面的问题)

@Test
public void executorPoolTest(){
    ExecutorService cachedThreadPool = 
            Executors.newFixedThreadPool(10);
    //Executors.newCachedThreadPool();  
    for (int i = 0; i < 1000; i++) {  
        final int index = i;  
        cachedThreadPool.execute(new Runnable() {  
            public void run() {  
                System.out.println(index);
                try {  
                    Thread.sleep( 5000); 
                    System.out.println(index+"_");
                } catch (InterruptedException e) {  
                    e.printStackTrace();  
                }  
            }  
        });  
    }
    //no matter whether you call shutdown, the above program will ends quickly.
    cachedThreadPool.shutdown();

}

上面的程序不打印任何数字+“_”,很奇怪。 但是,如果上面的方法在main方法中运行(我的意思是:public static void main(String[] args)),行为是正常的,线程会休眠并且可以打印“_”。

我想知道为什么? junit框架发生了什么?如果是这样,我不能使用 junit 来测试 executor 涉及的方法吗?

junit 版本是 4.12。

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

【问题讨论】:

    标签: java multithreading junit executorservice thread-sleep


    【解决方案1】:

    是的,因为您无需等待已安排完成的任务。如果您有其他单元测试,您创建的线程仍将继续在后台执行,但您的测试将完成,因为您没有告诉它做任何其他事情。如果这是您唯一的测试,则没有任何东西可以使进程保持活动状态,因此测试套件将在没有线程输出的情况下完成。

    如果你在关机后调用awaitTermination那么它会在测试完成之前等待所有线程完成。

    【讨论】:

    • 啊,我明白了!你的意思是,Junit 的主线程结束了,因此,这个测试单元中的线程结束了。
    猜你喜欢
    • 2010-11-08
    • 2020-09-27
    • 1970-01-01
    • 1970-01-01
    • 2011-06-23
    • 2015-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多