1.19 实现一个容器, 有两个要求: 1. add(), size(). 2. 写2个线程, 线程1添加10个元素到容器中, 线程2实现监控元素个数, 当个数到达5个时, 线程2给出提示并结束...

/**
 * This is description.
 * 面试题: 实现一个容器, 有两个要求:
 * 1. add, size.
 * 2. 写2个线程, 线程1添加10个元素到容器中, 线程2实现监控元素个数, 当个数到达5个时, 线程2给出提示并结束(线程2结束).
 * Container2在Container1基础上加了volatile关键字, 但是线程2采用了while(true){...}死循环, 很耗费CPU, 如果不采用死循环, 又该如何处理呢?
 * @author Chris Lee
 * @date 2019/3/14 22:20
 */
public class Container2 {
    volatile List list = new ArrayList<>(10);

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

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

    public static void main(String[] args) {
        Container2 container1 = new Container2();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                container1.add(new Object());
                System.out.println("当前线程名: " + Thread.currentThread().getName() + ", i = " + i);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "t1").start();

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

        new Thread(() -> {
            while (true) {
                if (container1.size() == 5) {
                    break;
                }
            }
            System.out.println("当前线程名: " + Thread.currentThread().getName());

        }, "t2").start();
    }
    /*
        当前线程名: t1, i = 0
        当前线程名: t1, i = 1
        当前线程名: t1, i = 2
        当前线程名: t1, i = 3
        当前线程名: t1, i = 4
        当前线程名: t2
        当前线程名: t1, i = 5
        当前线程名: t1, i = 6
        当前线程名: t1, i = 7
        当前线程名: t1, i = 8
        当前线程名: t1, i = 9

     */
}

说明:
  • 本篇文章如有不正确或待改进的地方, 欢迎批评和指正, 大家一同进步, 谢谢!
  • 世上有4样东西可以让世界变得更美好, 它们是: 代码(Code), 诗(Poem), 音乐(Music), 爱(Love). 如有兴趣了解更多, 欢迎光顾"我的文集"相关文章.
资料:
  1. 学习视频: https://www.bilibili.com/video/av11076511/?p=1
  2. 参考代码: https://github.com/EduMoral/edu/tree/master/concurrent/src/yxxy
  3. 我的代码: https://github.com/ChrisLeejing/learn_concurrency.git

你可能感兴趣的:(1.19 实现一个容器, 有两个要求: 1. add(), size(). 2. 写2个线程, 线程1添加10个元素到容器中, 线程2实现监控元素个数, 当个数到达5个时, 线程2给出提示并结束...)