經典筆試題:監控容器元素的數量(採用CountDownLatch實現)
阿新 • • 發佈:2020-09-02
筆試題:
實現一個容器,提供兩個方法:add,size
寫兩個執行緒,執行緒1新增10個元素到容器中,執行緒2實現監控元素的個數,當個數到5時,執行緒2給出提示並結束
import java.util.ArrayList;
import java.util.List;
public class Container {
List<Object> container = new ArrayList<>();
public void add(Object o) {
this.container.add(o);
}
public int size() {
return this.container.size();
}
}
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class Test {
public static void main(String[] args) {
Container container = new Container();
CountDownLatch latch = new CountDownLatch(1);
new Thread(() -> {
System.out.println("t1啟動");
for (int i = 0; i < 10; i++) {
container.add(new Object());
System.out.println("add " + i);
if (container.size() == 5) {
latch.countDown();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
System.out.println("t1 結束");
}, "t1").start();
new Thread(() -> {
System.out.println("t2啟動");
if (container.size() != 5) {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("size=5");
System.out.println("t2 結束");
}, "t2").start();
}
}
執行結果:
t1啟動
add 0
t2啟動
add 1
add 2
add 3
add 4
size=5
t2 結束
add 5
add 6
add 7
add 8
add 9
t1 結束