JAVA多线程---Condition使用---线程通信

线程之间除了同步互斥,还要考虑通信。在Java5之前我们的通信方式为:wait 和 notify。 那么Condition的优势是支持多路等待,就是我可以定义多个Condition,每个condition控制线程的一条执行通路。传统方式只能是一路等待。我们可以先分析下Java5 Api中的缓冲队列的实现:

假定有一个绑定的缓冲区,它支持 puttake 方法。如果试图在空的缓冲区上执行take 操作,则在某一个项变得可用之前,线程将一直阻塞;如果试图在满的缓冲区上执行put 操作,则在有空间变得可用之前,线程将一直阻塞。我们喜欢在单独的等待 set 中保存put 线程和take 线程,这样就可以在缓冲区中的项或空间变得可用时利用最佳规划,一次只通知一个线程。可以使用两个Condition  实例来做到这一点。

Java代码
  1. class BoundedBuffer {  
  2.            final Lock lock = new ReentrantLock();//实例化一个锁对象  
  3.            final Condition notFull  = lock.newCondition(); //实例化两个condition  
  4.            final Condition notEmpty = lock.newCondition();   
  5.   
  6.            final Object[] items = new Object[100];//初始化一个长度为100的队列  
  7.            int putptr, takeptr, count;  
  8.   
  9.            public void put(Object x) throws InterruptedException {  
  10.              lock.lock();//获取锁  
  11.              try {  
  12.                while (count == items.length)   
  13.                  notFull.await();//当计数器count等于队列的长度时,不能在插入,因此等待  
  14.                items[putptr] = x; //将对象放入putptr索引处  
  15.                if (++putptr == items.length) putptr = 0;//当索引长度等于队列长度时,将putptr置为0  
  16.                //原因是,不能越界插入  
  17.                ++count;//没放入一个对象就将计数器加1  
  18.                notEmpty.signal();//一旦插入就唤醒取数据线程  
  19.              } finally {  
  20.                lock.unlock();//最后释放锁  
  21.              }  
  22.            }  
  23.   
  24.            public Object take() throws InterruptedException {  
  25.              lock.lock();//获取锁  
  26.              try {  
  27.                while (count == 0//如果计数器等于0那么等待  
  28.                  notEmpty.await();  
  29.                Object x = items[takeptr]; //取得takeptr索引处对象  
  30.                if (++takeptr == items.length) takeptr = 0;//当takeptr达到队列长度时,从零开始取  
  31.                --count;//每取一个讲计数器减1  
  32.                notFull.signal();//枚取走一个就唤醒存线程  
  33.                return x;  
  34.              } finally {  
  35.                lock.unlock();//释放锁  
  36.              }  
  37.            }   
  38.          }

下面还有一个例子:

启动main,sub2,sub3三个线程,sub2运行完后sub3运行,sub3运行完成后main运行,main运行完成后sub2运行,如此循环往复50次。实现代码如下:

Java代码
  1. import java.util.concurrent.locks.Condition;  
  2. import java.util.concurrent.locks.Lock;  
  3. import java.util.concurrent.locks.ReentrantLock;  
  4.   
  5. public class ConditionCommunication {  
  6.   
  7.     /** 
  8.      * @param args 
  9.      */  
  10.     public static void main(String[] args) {  
  11.           
  12.         final Business business = new Business();  
  13.           
  14.         new Thread(new Runnable(){  
  15.   
  16.             public void run() {  
  17.                 for(int i=0; i<50; i++){  
  18.                     business.sub2(i);  
  19.                 }  
  20.             }  
  21.               
  22.         }).start();  
  23.           
  24.         new Thread(new Runnable(){  
  25.   
  26.             public void run() {  
  27.                 for(int i=0; i<50; i++){  
  28.                     business.sub3(i);  
  29.                 }  
  30.             }  
  31.               
  32.         }).start();  
  33.           
  34.           
  35.         new Thread(new Runnable(){  
  36.   
  37.             public void run() {  
  38.                 for(int i=0; i<50; i++){  
  39.                     business.main(i);  
  40.                 }  
  41.             }  
  42.               
  43.         }).start();  
  44.           
  45.     }  
  46.       
  47.       
  48.       
  49.     static class Business{  
  50.           
  51.         private int shouldSub = 1;  
  52.           
  53.         private Lock lock = new ReentrantLock();  
  54.           
  55.         Condition condition1 = lock.newCondition();  
  56.           
  57.         Condition condition2 = lock.newCondition();  
  58.           
  59.         Condition condition3 = lock.newCondition();  
  60.           
  61.           
  62.         public void sub2(int i){  
  63.             try{  
  64.                 lock.lock();  
  65.                 while(shouldSub != 2){  
  66.                     try {  
  67.     //                  this.wait();  
  68.                         condition2.await();  
  69.                     } catch (Exception e) {  
  70.                         e.printStackTrace();  
  71.                     }  
  72.                 }  
  73.                 for(int j=1; j<=10; j++){  
  74.                     System.out.println("sub2 thread sequence is " + j + " loop of " + i);  
  75.                 }  
  76.                 shouldSub = 3;  
  77.     //          this.notify();  
  78.                 condition3.signal();  
  79.             }finally{  
  80.                 lock.unlock();  
  81.             }  
  82.         }  
  83.           
  84.           
  85.         public void sub3(int i){  
  86.             try{  
  87.                 lock.lock();  
  88.                 while(shouldSub != 3){  
  89.                     try {  
  90.     //                  this.wait();  
  91.                         condition3.await();  
  92.                     } catch (Exception e) {  
  93.                         e.printStackTrace();  
  94.                     }  
  95.                 }  
  96.                 for(int j=1; j<=20; j++){  
  97.                     System.out.println("sub3 thread sequence is " + j + " loop of " + i);  
  98.                 }  
  99.                 shouldSub = 1;  
  100.     //          this.notify();  
  101.                 condition1.signal();  
  102.             }finally{  
  103.                 lock.unlock();  
  104.             }  
  105.         }  
  106.           
  107.           
  108.           
  109.         public void main(int i){  
  110.             try{  
  111.                 lock.lock();  
  112.                 while(shouldSub != 1){  
  113.                     try {  
  114. //                      this.wait();  
  115.                         condition1.await();  
  116.                     } catch (Exception e) {  
  117.                         e.printStackTrace();  
  118.                     }  
  119.                 }  
  120.                 for(int j=1; j<=100; j++){  
  121.                     System.out.println("main thread sequence is " + j + " loop of " + i);  
  122.                 }  
  123.                 shouldSub = 2;  
  124. //              this.notify();  
  125.                 condition2.signal();  
  126.             }finally{  
  127.                 lock.unlock();  
  128.             }  
  129.         }  
  130.     }  
  131.   
  132. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值