gpt4 book ai didi

java - 在多线程环境中使用 JUnit 的奇怪问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:16:43 24 4
gpt4 key购买 nike

在多线程环境中使用 JUnit 时,我遇到了一个奇怪的问题。下面的代码应该会失败,但实际上在eclipse中通过了。

public class ExampleTest extends TestCase {

private ExecutorService executor = Executors.newFixedThreadPool(10);

private volatile boolean isDone = false;

public void test() throws InterruptedException, ExecutionException {
executor.submit(new Runnable() {

@Override
public void run() {
try {
fail();
} finally {
isDone = true;
}
}
});

while (!isDone) {
Thread.sleep(1000);
}
}
}

这是另一段代码,这里我使用 Future.get() 来等待线程停止,在这种情况下它会失败。

public class ExampleTest extends TestCase {

private ExecutorService executor = Executors.newFixedThreadPool(10);

private volatile boolean isDone = false;

public void test() throws InterruptedException, ExecutionException {
Future future=executor.submit(new Runnable() {

@Override
public void run() {
try {
fail();
} finally {
isDone = true;
}
}
});

future.get();
}
}

我google了一下,发现JUnit不能处理多线程单元测试,但是这两段代码有什么区别呢?谢谢

最佳答案

JUnit 看不到运行测试的线程以外的线程中发生的异常。在第一种情况下,通过调用 fail 发生异常,它发生在由 executor 运行的单独线程中。因此它对 JUnit 不可见并且测试通过。

在第二种情况下,同样的异常发生在由 executor 运行的单独线程中,但是当您调用 future.get< 时,异常会有效地“报告回”给测试线程。这是因为如果 future 的计算由于任何异常而失败,future.get 将抛出一个 ExecutionException。 JUnit 能够看到此异常,因此测试失败。

关于java - 在多线程环境中使用 JUnit 的奇怪问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4039873/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com