读书人

Condition 在多线程合作中应用实例

发布时间: 2014-01-17 15:01:00 作者: rapoo

Condition 在多线程协作中应用实例
import java.util.ArrayList;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.locks.Condition;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReentrantLock;public class NewestPlate {private List<Object> eggs = new ArrayList<Object>();private Lock lock = new ReentrantLock();private Condition addCond = lock.newCondition();private Condition getCond = lock.newCondition();public Object getEgg() {lock.lock();try {while(eggs.size() == 0) {try {getCond.await();} catch (Exception e) {e.printStackTrace();}}Object egg = eggs.get(0);eggs.clear(); //清空addCond.signalAll();System.out.println("拿到鸡蛋");return egg;} finally {lock.unlock();}}public void addEgg(Object egg) {lock.lock();try {while(eggs.size() > 0) {try {addCond.await();} catch (Exception e) {e.printStackTrace();}}eggs.add(egg);getCond.signalAll();System.out.println("放入鸡蛋");} finally {lock.unlock();}}public static void main(String[] args) {Plate plate = new Plate();ExecutorService exec = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {exec.execute(new AddEggThread(plate));exec.execute(new GetEggThread(plate));}exec.shutdown();}}

?Condition 可以用来挂起、唤醒某个指定的线程。

1 楼 bo_hai 19 小时前 Condition的强大之处在于它可以为多个线程间建立不同的Condition

读书人网 >编程

热点推荐