经典笔试题:线程通信(使用wait,notify实现线程间通信)
经典笔试题:
1、自定义容器,提供新增元素(add)和获取元素数量(size)方法。
2、启动两个线程。线程1向容器中新增10个数据。线程2监听容器元素数量,当容器元素数量为5时,线程2输出信息并终止。
package com.gaopeng.programming.test2; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; /** * 练习:使用wait,notify实现线程间通信 * 自定义容器,提供新增元素(add)和获取元素数量(size)方法。 * 启动两个线程。线程1向容器中新增10个数据。线程2监听容器元素数量,当容器元素数量为5时,线程2输出信息并终止。 */ public class Test02 { public static void main(String[] args) { final Test02Container myContainer = new Test02Container(); final Object lock = new Object(); new Thread(new Runnable() { @Override public void run() { synchronized (lock) { System.out.println(Thread.currentThread().getName() + "获得锁"); if (myContainer.size() != 5) { try { System.out.println(Thread.currentThread().getName() + "释放锁"); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("size = 5"); lock.notifyAll(); // 唤醒其他等待线程 } } }).start(); new Thread(new Runnable() { @Override public void run() { synchronized (lock) { System.out.println(Thread.currentThread().getName() + "获得锁"); for (int i = 1; i <= 10; i++) { System.out.println("add Object to Container " + i); myContainer.add(new Object()); if (myContainer.size() == 5) { lock.notifyAll(); try { System.out.println(Thread.currentThread().getName() + "释放锁"); lock.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } } }).start(); } } class Test02Container { List<Object> container = new ArrayList<>(); public void add(Object o) { this.container.add(o); } public int size() { return this.container.size(); } }
运行结果如下:
Thread-0获得锁
Thread-0释放锁
Thread-1获得锁
add Object to Container 1
add Object to Container 2
add Object to Container 3
add Object to Container 4
add Object to Container 5
Thread-1释放锁
size = 5
add Object to Container 6
add Object to Container 7
add Object to Container 8
add Object to Container 9
add Object to Container 10