JAVA5多线程---Condition使用---线程通信 --wait及notify方法

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

假定有一个绑定的缓冲区,它支持 put 和 take 方法。如果试图在空的缓冲区上执行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. }  

















Java 多线程(七) 线程间的通信——wait及notify方法

 

线程间的相互作用

  线程间的相互作用:线程之间需要一些协调通信,来共同完成一件任务。

  Object类中相关的方法有两个notify方法和三个wait方法:

  http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

  因为wait和notify方法定义在Object类中,因此会被所有的类所继承。

  这些方法都是final的,即它们都是不能被重写的,不能通过子类覆写去改变它们的行为。

 

wait()方法

  wait()方法使得当前线程必须要等待,等到另外一个线程调用notify()或者notifyAll()方法。

  当前的线程必须拥有当前对象的monitor,也即lock,就是锁。

  线程调用wait()方法,释放它对锁的拥有权,然后等待另外的线程来通知它(通知的方式是notify()或者notifyAll()方法),这样它才能重新获得锁的拥有权和恢复执行。

  要确保调用wait()方法的时候拥有锁,即,wait()方法的调用必须放在synchronized方法或synchronized块中。

 

  一个小比较:

  当线程调用了wait()方法时,它会释放掉对象的锁。

  另一个会导致线程暂停的方法:Thread.sleep(),它会导致线程睡眠指定的毫秒数,但线程在睡眠的过程中是不会释放掉对象的锁的。

 

notify()方法

  notify()方法会唤醒一个等待当前对象的锁的线程。

  如果多个线程在等待,它们中的一个将会选择被唤醒。这种选择是随意的,和具体实现有关。(线程等待一个对象的锁是由于调用了wait方法中的一个)。

  被唤醒的线程是不能被执行的,需要等到当前线程放弃这个对象的锁。

  被唤醒的线程将和其他线程以通常的方式进行竞争,来获得对象的锁。也就是说,被唤醒的线程并没有什么优先权,也没有什么劣势,对象的下一个线程还是需要通过一般性的竞争。

  notify()方法应该是被拥有对象的锁的线程所调用。

  (This method should only be called by a thread that is the owner of this object's monitor.)

  换句话说,和wait()方法一样,notify方法调用必须放在synchronized方法或synchronized块中。

 

  wait()和notify()方法要求在调用时线程已经获得了对象的锁,因此对这两个方法的调用需要放在synchronized方法或synchronized块中。

  一个线程变为一个对象的锁的拥有者是通过下列三种方法:

  1.执行这个对象的synchronized实例方法。

  2.执行这个对象的synchronized语句块。这个语句块锁的是这个对象。

  3.对于Class类的对象,执行那个类的synchronized、static方法。

 

程序实例

  利用两个线程,对一个整形成员变量进行变化,一个对其增加,一个对其减少,利用线程间的通信,实现该整形变量0101这样交替的变更。

复制代码
public class NumberHolder
{
    private int number;

    public synchronized void increase()
    {
        if (0 != number)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        // 能执行到这里说明已经被唤醒
        // 并且number为0
        number++;
        System.out.println(number);

        // 通知在等待的线程
        notify();
    }

    public synchronized void decrease()
    {
        if (0 == number)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

        }

        // 能执行到这里说明已经被唤醒
        // 并且number不为0
        number--;
        System.out.println(number);
        notify();
    }

}



public class IncreaseThread extends Thread
{
    private NumberHolder numberHolder;

    public IncreaseThread(NumberHolder numberHolder)
    {
        this.numberHolder = numberHolder;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; ++i)
        {
            // 进行一定的延时
            try
            {
                Thread.sleep((long) Math.random() * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            // 进行增加操作
            numberHolder.increase();
        }
    }

}



public class DecreaseThread extends Thread
{
    private NumberHolder numberHolder;

    public DecreaseThread(NumberHolder numberHolder)
    {
        this.numberHolder = numberHolder;
    }

    @Override
    public void run()
    {
        for (int i = 0; i < 20; ++i)
        {
            // 进行一定的延时
            try
            {
                Thread.sleep((long) Math.random() * 1000);
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

            // 进行减少操作
            numberHolder.decrease();
        }
    }

}



public class NumberTest
{
    public static void main(String[] args)
    {
        NumberHolder numberHolder = new NumberHolder();
        
        Thread t1 = new IncreaseThread(numberHolder);
        Thread t2 = new DecreaseThread(numberHolder);
                
        t1.start();
        t2.start();
    }

}
复制代码

  

  如果再多加上两个线程呢?

  即把其中的NumberTest类改为如下:

复制代码
public class NumberTest
{
    public static void main(String[] args)
    {
        NumberHolder numberHolder = new NumberHolder();
        
        Thread t1 = new IncreaseThread(numberHolder);
        Thread t2 = new DecreaseThread(numberHolder);
        
        Thread t3 = new IncreaseThread(numberHolder);
        Thread t4 = new DecreaseThread(numberHolder);
                
        t1.start();
        t2.start();
        
        t3.start();
        t4.start();
    }

}
复制代码

 

  运行后发现,加上t3和t4之后结果就错了。

  为什么两个线程的时候执行结果正确而四个线程的时候就不对了呢?

  因为线程在wait()的时候,接收到其他线程的通知,即往下执行,不再进行判断。两个线程的情况下,唤醒的肯定是另一个线程;但是在多个线程的情况下,执行结果就会混乱无序。

  比如,一个可能的情况是,一个增加线程执行的时候,其他三个线程都在wait,这时候第一个线程调用了notify()方法,其他线程都将被唤醒,然后执行各自的增加或减少方法。

  解决的方法就是:在被唤醒之后仍然进行条件判断,去检查要改的数字是否满足条件,如果不满足条件就继续睡眠。把两个方法中的if改为while即可。

复制代码
public class NumberHolder
{
    private int number;

    public synchronized void increase()
    {
        while (0 != number)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }

        // 能执行到这里说明已经被唤醒
        // 并且number为0
        number++;
        System.out.println(number);

        // 通知在等待的线程
        notify();
    }

    public synchronized void decrease()
    {
        while (0 == number)
        {
            try
            {
                wait();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }

        }

        // 能执行到这里说明已经被唤醒
        // 并且number不为0
        number--;
        System.out.println(number);
        notify();
    }

}
复制代码

 

 

参考资料

  圣思园张龙老师Java SE系列视频教程。


NumberThread 类是负责循环输出数字 1-26 的线程一
UpperCharThread 类是负责循环输出大写字母 A-Z 的线程二
LowerCharThread 类是负责循环输出小写字母 a-z 的线程三

现在要实现的是一次输出 数字、大写字母、小写

如:
1 A a
2 B b
. . .
. . .
26 Z z

使用synchronized 和 wait() notify() 完成






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值