@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@Transactional@SpringApplicationConfiguration(Application.class)public class Main {
static Log logger = LogFactory.getLog(Main.class);
@Test
public void test() {
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(11);
for (int i = 0; i < 10; i++) {
fixedThreadPool.execute(new Runnable() {
@Override
public void run() {
System.out.println("a");
}
});
}
System.out.println("b");
}
为什么输出结果是ab,而不是10个a和1个b
1 回答
慕码人8056858
TA贡献1803条经验 获得超6个赞
单元测试运行结束后会强制退出进程。所以剩下的线程并不会执行。你可以使用下面的示例等待所有任务执行完成。
ExecutorService executorService = Executors.newFixedThreadPool(11);
CountDownLatch latch = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
final int v = i;
executorService.execute(() -> {
latch.countDown();
System.out.println(v + " - a");
});
}
System.out.println("b");
try {
// 等待所有任务结束
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
添加回答
举报
0/150
提交
取消