package cn.com.servyou.qysdsjx.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * daieweb * <p> * Created by haozb on 2017/9/28. */ public class Plate { /** 装鸡蛋的盘子 */ List<Object> eggs = new ArrayList<Object>(); Lock lock = new ReentrantLock(); Condition get = lock.newCondition(); Condition set = lock.newCondition(); /** 取鸡蛋 */ public Object getEgg() { try { lock.lock(); while (eggs.size() == 0) { try { //wait(); //lock.wait(); get.await(); } catch (InterruptedException e) { e.printStackTrace(); } } Object egg = eggs.get(0); eggs.clear();// 清空盘子 set.signal(); System.out.println("拿到鸡蛋"); return egg; } catch (Exception e) { }finally { lock.unlock(); } return eggs; } /** 放鸡蛋 */ public void putEgg(Object egg) { try { lock.lock(); while (eggs.size() > 0) { try { set.await(); } catch (InterruptedException e) { e.printStackTrace(); } } eggs.add(egg);// 往盘子里放鸡蛋 get.signal(); System.out.println("放入鸡蛋"); } catch (Exception e) { }finally { lock.unlock(); } } static class AddThread implements Runnable { private Plate plate; private Object egg = new Object(); public AddThread(Plate plate) { this.plate = plate; } public void run() { plate.putEgg(egg); } } static class GetThread implements Runnable { private Plate plate; public GetThread(Plate plate) { this.plate = plate; } public void run() { plate.getEgg(); } } public static void main(String args[]) { Plate plate = new Plate(); for(int i = 0; i < 10; i++) { new Thread(new AddThread(plate)).start(); new Thread(new GetThread(plate)).start(); } } }