[英]Thread.sleep causing unexpected behavior in ExecutorService loop
In below test class just "before" is outputted. 在下面的测试类中,仅输出“之前”。
But if I removed Thread.sleep the following is outputted : 但是,如果我删除Thread.sleep,则会输出以下内容:
before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after
before
after
Which is what I expect. 这是我所期望的。
When I use Thread.sleep I think that there should be a 1000ms delay between each output of 当我使用Thread.sleep时,我认为每个输出之间应该有1000ms的延迟
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 ? 为什么不会发生这种情况?如何修改代码,以使生成的输出是相同的,而不管是否调用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);
}
}
}
Update from reading comment below "@user470184 It doesn't work in junit test cases because Junit kills all threads when the main thread completes. – Sotirios Delimanolis" if I add 从下面的阅读评论中更新“ @ user470184,它在junit测试用例中不起作用,因为在主线程完成时Junit会杀死所有线程。– Sotirios Delimanolis”(如果添加)
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
at the end of test method then it works as expected. 在测试方法的最后,它可以按预期工作。
When I use Thread.sleep I think that there should be a 1000ms delay between each output of 当我使用Thread.sleep时,我认为每个输出之间应该有1000ms的延迟
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 ? 为什么不会发生这种情况?如何修改代码,以使生成的输出是相同的,而不管是否调用sleep?
The delay is clearly between before
and after
, not between each iteration of those 延迟之间显然before
和after
,而不是那些每次迭代之间
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. 您确实有一个1个线程的线程池。
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. 至于为什么JUnit失败,JUnit在其主线程完成执行时会杀死所有线程。 You cannot really control this (short of implementing your own wait mechanism). 您无法真正控制它(缺少实现自己的等待机制)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.