需求:
实现一个容器,提供两个方法,add,size,写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5个时,线程2给出提示并结束
public class MyContainer3 {
volatile List lists = new ArrayList<>();
void add(Object obj){
lists.add(obj);
}
int size(){
return lists.size();
}
public static void main(String[] args) {
MyContainer3 mc = new MyContainer3();
CountDownLatch latch = new CountDownLatch(1);
new Thread(() ->{
System.out.println("t2启动");
if (mc.size() != 5) {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("t2结束");
},"t2").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
mc.add(new Object());
if (5 == mc.size()) {
latch.countDown();
}
System.out.println("count = " + mc.size());
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"t1").start();
}
}
结果: