package com.umbrella.km; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; public class MyContainer { volatile List list = new ArrayList(); public void add(Object o) { list.add(o); } public int size() { return list.size(); } @Test public void test() { MyContainer mc = new MyContainer(); new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("add " + i); mc.add(new Object()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1").start(); new Thread(() -> { while (true) { if (mc.size() == 5) { break; } } System.out.println("t2 stop"); }, "t2").start(); } public static void main(String[] args) { MyContainer mc = new MyContainer(); new Thread(() -> { for (int i = 0; i < 10; i++) { System.out.println("add " + i); mc.add(new Object()); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } }, "t1").start(); new Thread(() -> { while (true) { if (mc.size() == 5) { break; } } System.out.println("t2 stop"); }, "t2").start(); } }
现在想要在t1线程的长度为5时,t2线程就终止。但只有main函数能正确执行,Junit的测试类就不行,为什么呢?
zzZerOrz
相关分类