码迷,mamicode.com
首页 > 其他好文 > 详细

条件阻塞Condition的应用

时间:2015-12-11 22:26:27      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

Condition的功能类似在传统线程技术中的Object.wait和Object.notity的功能。
 
例子:生产者与消费者
 
import java.util.Random;
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;
 
/**
 * 有时候线程取得lock后需要在一定条件下才能做某些工作,比如说经典的Producer和Consumer问题。 在Java
 * 5.0以前,这种功能是由Object类的wait(), notify()和notifyAll()等方法实现的,
 * 在5.0里面,这些功能集中到了Condition这个接口来实现。
 */
public class ConditionTest {
 
        /**
        * 篮子程序。Consumer必须在篮子里有苹果的时候才能吃苹果,否则它必须暂时放弃对篮子的锁定,
        * 等到Producer往篮子里放了苹果后再去拿来吃。而Producer必须等到篮子空了才能往里放苹果,
        * 否则它也需要暂时解锁等Consumer把苹果吃了才能往篮子里放苹果。
        */
        public static class Basket {
               // 锁
              Lock lock = new ReentrantLock();
               // 根据锁产生Condition对象
              Condition produced = lock .newCondition();
              Condition consumed = lock .newCondition();
               // 篮子中的苹果数
               int num = 0;
               // 篮子中的最多放的苹果数
               int count = 5;
 
               /**
               * 生产苹果,往篮子里放
               *
               * @throws InterruptedException
               */
               public void produce() throws InterruptedException {
                      // 获得锁
                      lock.lock();
                     System. out.println("Producer get a lock..." );
                      try {
                            // 判断是否满足生产条件
                            while (num == count) {
                                   // 如果有苹果,则不生产,放弃锁,进入睡眠
                                   // 等待消费者消费
                                  System. out.println("Producer sleep..." );
                                   consumed.await();
                                  System. out.println("Producer awaked..." );
                           }
                            /* 生产苹果 */
                           Thread. sleep(new Random().nextInt(50));
                           System. out.println("Producer produced an Apple." );
                            num++;
                           System. out.println("Producer 篮子里有" + num + "个苹果" );
                            // 通知等待produced Condition的线程
                            produced.signal();
                     } finally {
                            lock.unlock();
                     }
              }
 
               /**
               * 消费苹果,从篮子中取
               *
               * @throws InterruptedException
               */
               public void consume() throws InterruptedException {
                      // 获得锁
                      lock.lock();
                     System. out.println("Consumer get a lock..." );
                      try {
                            // 判断是否满足消费条件
                            while (num == 0) {
                                   // 如果没有苹果,无法消费,则放弃锁,进入睡眠
                                   // 等待生产者生产苹果
                                  System. out.println("Consumer sleep..." );
                                   produced.await();
                                  System. out.println("Consumer awaked..." );
                           }
                            /* 吃苹果 */
                           Thread. sleep(new Random().nextInt(500));
                           System. out.println("Consumer consumed an Apple." );
                            num--;
                           System. out.println("Consumer 篮子里剩" + num + "个苹果" );
                            // 发信号唤醒某个等待consumed Condition的线程
                            consumed.signal();
                     } finally {
                            lock.unlock();
                     }
              }
       }
 
        /**
        * 测试Basket程序
        */
        public static void testBasket() throws Exception {
               final Basket basket = new Basket();
               // 定义一个producer
              Runnable producer = new Runnable() {
                      public void run() {
                            try {
                                  basket.produce();
                           } catch (InterruptedException ex) {
                                  ex.printStackTrace();
                           }
                     }
              };
 
               // 定义一个consumer
              Runnable consumer = new Runnable() {
                      public void run() {
                            try {
                                  basket.consume();
                           } catch (InterruptedException ex) {
                                  ex.printStackTrace();
                           }
                     }
              };
 
               // 各产生10个consumer和producer
              ExecutorService service = Executors. newCachedThreadPool();
               for (int i = 0; i < 10; i++) {
                     service.execute(producer);
              }
               for (int i = 0; i < 10; i++) {
                     service.execute(consumer);
              }
              service.shutdown();
       }
 
        public static void main(String[] args) throws Exception {
              ConditionTest. testBasket();
       }
}

条件阻塞Condition的应用

标签:

原文地址:http://www.cnblogs.com/tstd/p/5040269.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!