/**
* This is description.
* 面試題: 實(shí)現(xiàn)一個(gè)容器, 有兩個(gè)要求:
* 1. add, size.
* 2. 寫2個(gè)線程, 線程1添加10個(gè)元素到容器中, 線程2實(shí)現(xiàn)監(jiān)控元素個(gè)數(shù), 當(dāng)個(gè)數(shù)到達(dá)5個(gè)時(shí), 線程2給出提示并結(jié)束(線程2結(jié)束).
* Container3利用wait和notify優(yōu)化Container2的while(true){...}死循環(huán).
*
* @author Chris Lee
* @date 2019/3/16 9:59
*/
public class Container3 {
volatile 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) {
Container2 container1 = new Container2();
Object lock = new Object();
new Thread(() -> {
synchronized (lock) {
System.out.println("當(dāng)前線程名: " + Thread.currentThread().getName() + "啟動(dòng).");
if (container1.size() != 5) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("當(dāng)前線程名: " + Thread.currentThread().getName() + "結(jié)束.");
}
}, "t2").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
synchronized (lock) {
for (int i = 0; i < 10; i++) {
container1.add(new Object());
System.out.println("當(dāng)前線程名: " + Thread.currentThread().getName() + ", i = " + i);
if (container1.size() == 5) {
lock.notify();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}, "t1").start();
}
/*
當(dāng)前線程名: t2啟動(dòng).
當(dāng)前線程名: t1, i = 0
當(dāng)前線程名: t1, i = 1
當(dāng)前線程名: t1, i = 2
當(dāng)前線程名: t1, i = 3
當(dāng)前線程名: t1, i = 4
當(dāng)前線程名: t1, i = 5
當(dāng)前線程名: t1, i = 6
當(dāng)前線程名: t1, i = 7
當(dāng)前線程名: t1, i = 8
當(dāng)前線程名: t1, i = 9
當(dāng)前線程名: t2結(jié)束.
*/
}
說明:
- 本篇文章如有不正確或待改進(jìn)的地方, 歡迎批評(píng)和指正, 大家一同進(jìn)步, 謝謝!
- 世上有4樣?xùn)|西可以讓世界變得更美好, 它們是: 代碼(Code), 詩(Poem), 音樂(Music), 愛(Love). 如有興趣了解更多, 歡迎光顧"我的文集"相關(guān)文章.
資料:
- 學(xué)習(xí)視頻: 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