线程问题<2>

来源:互联网 发布:模拟人生2数据丢失 编辑:程序博客网 时间:2024/06/15 21:26

面试题:写一个固定容量同步容器,拥有put和get方法,以及getCount方法

能够支持2个生产者线程以及10个消费者线程的阻塞调用


1.使用wait和notify/notifyAll来实现

public class Test<T> {private LinkedList<T> list = new LinkedList<T>();private int MAX = 10;//最大容量private int count = 0;//当前容器的个数public synchronized void put(T t) {while(list.size() == MAX) {try {System.out.println("生产者进入了等待");this.wait();} catch (InterruptedException e) {e.printStackTrace();}}list.add(t);System.out.println("生产者生产了" + t);++count;this.notifyAll();}public synchronized <T> T get() {T t = null;while(list.size() == 0) {try {System.out.println("消费者进入了等待");this.wait();} catch (InterruptedException e) {e.printStackTrace();}}t = (T) list.removeFirst();System.out.println("消费者消费了" + t); --count;this.notifyAll();return t;}public static void main(String[] args) throws InterruptedException {final Test test = new Test();for (int i = 0; i < 10; i++) {new Thread() {public void run() {for (int j = 0; j < 5; j++) {test.get();}}}.start();}for (int i = 0; i < 2; i++) {new Thread() {public void run() {for (int j = 0; j < 35; j++) {test.put(j);}}}.start();}Thread.sleep(1000);System.out.println("容器中还有" + test.count + "个");}}


2.使用Lock和Condition来实现


public class Test51<T> {final private LinkedList<T> list = new LinkedList();private static int MAX = 10;private int count = 0;private Lock lock = new ReentrantLock();private Condition p = lock.newCondition();private Condition c = lock.newCondition();public void put(T t) {try {lock.lock();while(list.size() == MAX) {System.out.println("生产者进入等待");p.await();}list.add(t);System.out.println("生产者生产了" + t);++count;c.signalAll();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}}public <T> T get() {T t = null;try {lock.lock();while(list.size() == 0) {System.out.println("消费者进入等待");c.await();}t = (T) list.removeFirst();System.out.println("消费者消费了" + t);--count;p.signalAll();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}return t;}public static void main(String[] args) throws InterruptedException {final Test51 t = new Test51();for (int i = 0; i < 10; i++) {new Thread() {public void run() {for (int j = 0; j < 5; j++) {t.get();}}}.start();}for (int i = 0; i < 2; i++) {new Thread() {public void run() {for (int j = 0; j < 25; j++) {t.put(j);}}}.start();}Thread.sleep(1000);System.out.println("还剩余" + t.count);}}



原创粉丝点击