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