昨天学习redis的时候尝试去写一些测试用例,结果尝试模拟生产者消费者模式的时候出问题了,没有数据插入到redis,于是上来发了个问答https://ask.youkuaiyun.com/questions/764400 ,今天在用junit写多线程的时候也出现了这个问题,顿时恍然大悟——莫非是junit的问题,上网搜了一下果然如此
原因:
junit的源码
public static final int SUCCESS_EXIT = 0;
public static final int FAILURE_EXIT = 1;
public static final int EXCEPTION_EXIT = 2;
public static void main(String args[]) {
TestRunner aTestRunner = new TestRunner();
try {
TestResult r = aTestRunner.start(args);
if (!r.wasSuccessful())
System.exit(FAILURE_EXIT);
System.exit(SUCCESS_EXIT);
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(EXCEPTION_EXIT);
}
}
在末尾调用了system.exit,众所周知子线程会随着主线程的结束而结束。。找原因浪费我好多时间啊
解决方法:
可以使用较长市场的Sleep,或者使用CountDownLatch