笔试题:
实现一个容器,提供两个方法: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; public class Test { public static void main(String[] args) { Container container = new Container(); Object lock = new Object(); new Thread(() -> { System.out.println("t1启动"); synchronized (lock) { for (int i = 0; i < 10; i++) { container.add(new Object()); System.out.println("add " + i); if (container.size() == 5) { lock.notify(); try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } System.out.println("t1 结束"); }, "t1").start(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e1) { e1.printStackTrace(); } new Thread(() -> { System.out.println("t2启动"); synchronized (lock) { if (container.size() != 5) { try { lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("size = 5"); lock.notify(); } System.out.println("t2 结束"); }, "t2").start(); } }
运行结果:
t1启动
add 0
add 1
add 2
add 3
add 4
t2启动
size = 5
t2 结束
add 5
add 6
add 7
add 8
add 9
t1 结束
经典笔试题:监控容器元素的数量(采用wait和notify实现)
原文:https://www.cnblogs.com/gaopengpy/p/13598500.html