在下面的测试类中,仅输出“之前”。
但是,如果我删除了 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();
}
在测试方法结束时,它按预期工作。