1.19 实现一个容器, 有两个要求: 1. add(), s

2019-03-16  本文已影响0人  殊胜因缘_Chris
/**
 * This is description.
 * 面试题: 实现一个容器, 有两个要求:
 * 1. add, size.
 * 2. 写2个线程, 线程1添加10个元素到容器中, 线程2实现监控元素个数, 当个数到达5个时, 线程2给出提示并结束(线程2结束).
 *
 * @author Chris Lee
 * @date 2019/3/14 22:20
 */
public class Container1 {
    List<Object> list = new ArrayList<>(10);

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

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

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

        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
        当前线程名: t1, i = 5
        当前线程名: t1, i = 6
        当前线程名: t1, i = 7
        当前线程名: t1, i = 8
        当前线程名: t1, i = 9
     */
}
说明:
资料:
  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
上一篇下一篇

猜你喜欢

热点阅读