在多線程環境中使用JUnit時遇到了一個問題。下面的代碼應該會失敗,但它實際上在eclipse中傳遞。在多線程環境中使用JUnit時出現的奇怪問題
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? – zjffdu 2010-10-28 07:25:45