经典笔试题:监控容器元素的数量(采用CountDownLatch实现)

笔试题:
实现一个容器,提供两个方法:add,size
写两个线程,线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5时,线程2给出提示并结束

import java.util.ArrayList;
import java.util.List;

public class Container {
    List<Object> container = new ArrayList<>();

    public void add(Object o) {
        this.container.add(o);
    }

    public int size() {
        return this.container.size();
    }
}
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Test {

    public static void main(String[] args) {
        Container container = new Container();
        CountDownLatch latch = new CountDownLatch(1);

        new Thread(() -> {
            System.out.println("t1启动");
            for (int i = 0; i < 10; i++) {
                container.add(new Object());
                System.out.println("add " + i);

                if (container.size() == 5) {
                    latch.countDown();

                }

                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }

            }

            System.out.println("t1 结束");
        }, "t1").start();

        new Thread(() -> {
            System.out.println("t2启动");
            if (container.size() != 5) {
                try {
                    latch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("size=5");
            System.out.println("t2 结束");
        }, "t2").start();
    }
}

运行结果:

t1启动
add 0
t2启动
add 1
add 2
add 3
add 4
size=5
t2 结束
add 5
add 6
add 7
add 8
add 9
t1 结束

posted @ 2020-09-02 17:41  gaopengpy  阅读(174)  评论(0编辑  收藏  举报