Object类中的两个方法——wait和notify使用总结



    Object类中的wait 、和 notify方法是用来处理线程的方法,既然定义在Object类中,两个方法的重要程度可见一斑:

两个方法的使用上都很复杂:通过阅读API获得更多对方法的理解:

The current thread must own this object'smonitor. The thread releases ownership of this monitor and waits until anotherthread notifies threads waiting on this object's monitor to wake up eitherthrough a call to thenotify method or the notifyAll method. The thread then waits until it can re-obtain ownership ofthe monitor and resumes execution

 

 

“当前的线程必须要获得对象的锁!”

实现这个条件的做法就是wait 方法一定要定义在synchronized方法中或者synchronized代码块中;

线程必须要两次获得锁才能完全的执行synchronized中的所有内容;

当第一次调用到达wait方法时,The thread realeases ownership of this monitor and waituntil another thread notifies threads waiting on this …

线程会暂时释放锁的拥有权,等待其他线程的notify方法或者notifyAll方法唤醒该线程,继续执行代码!

 

 

 

30.

下面一个程序要求定义两个线程类,一个实现将目标加一,一个实现将目标减一,目标初始值为零,要求加一减一交替进行;

显然的单纯调用synchronized是无法满足条件的,需要使用wait,和notify方法;

 

package thread;

 

publicclass ThreadTest

{

 

   publicstaticvoid main(String[] args)

   {

      ThreadDemo2 demo = new ThreadDemo2();

      ThreadIncrease test1 = new ThreadIncrease(demo);

      ThreadDecrease test2 = new ThreadDecrease(demo);

      test1.start();

      test2.start();

   }

}

class ThreadDemo2

{

   privateintnum = 0;

   publicsynchronizedvoid Increase()

   {

      /*

       * 下面的代码是核心代码

       * 什么时候要让线程等待,当然是不符合条件的时候

       * 目的是想让num = 0 的时候才执行加一的操作,当num不等于零的时候会执行wait等待通知

       * 当通知num已经变为0时,wait结束,执行下面语句num++;

       * 然后执行notify方法!

       * 当然的一说Java中的synchronized总是伴随着waitnotify方法共同的存在;

       */

     

      if(num != 0)

      {

        try

        {

           wait();

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

      }

      num ++;

      System.out.println(num);

      notify();

      }

  

   publicsynchronizedvoid decrease()

   {

     

      if(num == 0)

      {

        try

        {

           wait();

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

      }

      num --;

      System.out.println(num);

     

      notify();

      }

     

  

}

class ThreadIncreaseextends Thread

{

   private ThreadDemo2demo;

   public ThreadIncrease(ThreadDemo2 demo)

   {

      this.demo = demo;

   }

   @Override

   publicvoid run()

   {

      for(int i = 0 ; i < 15; i ++)

      {

      demo.Increase();

      }

   }

  

}

class ThreadDecreaseextends Thread

{

   private ThreadDemo2demo;

   public ThreadDecrease(ThreadDemo2 demo)

   {

      this.demo = demo;

     

   }

   @Override

   publicvoid run()

   {

      for(int i = 0 ; i < 15; i ++)

      {

      demo.decrease();

      }

   }

}

 

 

 

31.

可惜的是上面的代码仍然有着致命的弱点,线程并不仅仅有两个,而且是两个相对的线程!

致命的弱点在于: 当线程在wait的时候它并不知道其他的线程到底做了什么!

现在我们将增加一个Increase线程类,和一个Decrease线程类

,并且调用它们的start方法运行后,你将看到这样的结果:

我们足以看到代码的脆弱性,为什么会出现这种情况,更糟糕的是结果是随机的!上面已经说得很清楚了:当线程在wait的时候,它不知道其他的线程正在做什么,

所以需要将代码变得更加健壮:

我们举一个为什么会出现这种情况的原因之一:

我们假设线程1、2调用增加方法,线程3、4调用减少方法

假设线程3 先访问了减少方法,因为此时num的值为0,所以wait,并且交出ownership,假设线程4又访问了减少方法,同样的wait,并且交出所有权,再假设线程1访问了增加方法,将num的值变为1,并且调用notify方法,假设notify了线程3,线程3将num的值变为0;并且notify,如果此时notify了线程4,那么悲剧就会发生了,线程4醒来后,会继续将num减一,变为-1,一步错,后面就全错了;

缺点就在于notify的随机性,所以在某个wait方法被唤醒时,增加判断条件,如果不符合条件,继续wait,显然 while循环是最合适的

!

全部的变化只需要将 if 改为 while!!

由于num是成员变量被线程共享,每当wait被唤醒,都会判断一次;

package thread;

 

publicclass ThreadTest

{

 

   publicstaticvoid main(String[] args)

   {

      ThreadDemo2 demo = new ThreadDemo2();

      ThreadIncrease test1 = new ThreadIncrease(demo);

      ThreadDecrease test2 = new ThreadDecrease(demo);

      ThreadIncrease test3 = new ThreadIncrease(demo);

      ThreadDecrease test4 = new ThreadDecrease(demo);

      test1.start();

      test2.start();

      test3.start();

      test4.start();

   }

}

class ThreadDemo2

{

   privateintnum = 0;

   publicsynchronizedvoid Increase()

   {

      /*

       * 下面的代码是核心代码

       * 什么时候要让线程等待,当然是不符合条件的时候

       * 目的是想让num = 0 的时候才执行加一的操作,当num不等于零的时候会执行wait等待通知

       * 当通知num已经变为0时,wait结束,执行下面语句num++;

       * 然后执行notify方法!

       * 当然的一说Java中的synchronized总是伴随着waitnotify方法共同的存在;

       */

     

      while(num != 0)

      {

        try

        {

           wait();

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

      }

      num ++;

      System.out.println(num);

      notify();

      }

  

   publicsynchronizedvoid decrease()

   {

     

      while(num == 0)

      {

        try

        {

           wait();

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

      }

      num --;

      System.out.println(num);

     

      notify();

      }

     

  

}

class ThreadIncreaseextends Thread

{

   private ThreadDemo2demo;

   public ThreadIncrease(ThreadDemo2 demo)

   {

      this.demo = demo;

   }

   @Override

   publicvoid run()

   {

      for(int i = 0 ; i < 15; i ++)

      {

        try

        {

           Thread.sleep((long)(Math.random()*1000));

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

        demo.Increase();

      }

   }

  

}

class ThreadDecreaseextends Thread

{

   private ThreadDemo2demo;

   public ThreadDecrease(ThreadDemo2 demo)

   {

      this.demo = demo;

     

   }

   @Override

   publicvoid run()

   {

      for(int i = 0 ; i < 15; i ++)

      {

        try

        {

           Thread.sleep((long)(Math.random()*1000));

        }

        catch (InterruptedException e)

        {

           // TODO Auto-generatedcatch block

           e.printStackTrace();

        }

        demo.decrease();

      }

   }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值