标签:exception 添加 null stat read 容器 ati col unp
笔试题:
实现一个容器,提供两个方法: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.TimeUnit; import java.util.concurrent.locks.LockSupport; public class Test6 { public static void main(String[] args) { Container container = new Container(); Thread t1 = null; Thread t2 = new Thread(() -> { System.out.println("t2启动"); if (container.size() != 5) { LockSupport.park(); } System.out.println("size=5"); System.out.println("t2 结束"); }, "t2"); t2.start(); t1 = 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) { LockSupport.unpark(t2); } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } } System.out.println("t1 结束"); }, "t1"); t1.start(); } }
运行结果:
t2启动
t1启动
add 0
add 1
add 2
add 3
add 4
size=5
t2 结束
add 5
add 6
add 7
add 8
add 9
t1 结束
经典笔试题:监控容器元素的数量(采用LockSupport实现)
标签:exception 添加 null stat read 容器 ati col unp
原文地址:https://www.cnblogs.com/gaopengpy/p/13603160.html