经典并发面试题

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

实现案例:

/**
 * @program: mystudy_basis
 * @description: 实现一个容器,提供俩个方法,add和size,写俩个线程,
 * 线程1添加10个元素到容器中,线程2实现监控元素的个数,当个数到5时,线程2给出提示并结束
 **/
public class ContainerTest {
    /**初始化容器*/
    volatile List<Object> list = new ArrayList<>();

    public void add(Object o){
        list.add(o);
    }

    public int size(){
       return list.size();
    }

    public static void main(String args[]){
        CountDownLatch countDownLatch = new CountDownLatch(1);
        ContainerTest containerTest = new ContainerTest();
        new Thread(()->{
            System.out.println("t2启动-----");
            if(containerTest.size()!=5){
                try {
                    countDownLatch.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("t2结束-----");
        },"t2").start();

        new Thread(()->{
            System.out.println("t1启动---");
            for(int i=0;i<10;i++){
                containerTest.add(new Object());
                System.out.println("add"+i);
                if(containerTest.size()==5){
                    countDownLatch.countDown();
                }
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t1").start();
    }
}

当CountDownLatch的值为0的时候,t2开始执行

posted @ 2019-12-30 14:17  小小吸血鬼  阅读(164)  评论(0编辑  收藏  举报