2

在下面的测试类中,仅输出“之前”。

但是,如果我删除了 Thread.sleep,则会输出以下内容:

before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after

这是我所期望的。

当我使用 Thread.sleep 时,我认为每个输出之间应该有 1000ms 的延迟

before
after

为什么这不会发生?如何修改代码以使生成的输出相同,无论是否调用 sleep ?

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.junit.Test;

public class RunExecutorTest {

    private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

    private class RunTest implements Runnable {
        public void run() {

            System.out.println("before");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.println("after");
        }
    }

    @Test
    public void testRun() {

        Runnable r = new RunTest();

        for(int counter = 0; counter < 10; ++counter) {  
            executor.execute(r);
        }
    }

}

从阅读下面的评论更新“@user470184 它在 junit 测试用例中不起作用,因为当主线程完成时,Junit 会杀死所有线程。 – Sotirios Delimolis”如果我添加

try {
    Thread.sleep(10000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

在测试方法结束时,它按预期工作。

4

1 回答 1

4

When I use Thread.sleep I think that there should be a 1000ms delay between each output of

before after

Why is this not occuring & how can the code be amended so that the generated output is same regardless of calling sleep or not ?

The delay is clearly between before and after, not between each iteration of those

System.out.println("before");

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

System.out.println("after");

yielding

before
...1000 millis
after
before
...1000 millis
after

Perhaps I've misunderstood your question.

You do have a Thread pool of 1 thread.

private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

All of this will be output sequentially.


As for why it's failing with JUnit, JUnit kills all threads when its main Thread completes execution. You cannot really control this (short of implementing your own wait mechanism).

于 2013-09-18T19:15:02.910 回答