现在的位置: 首页 > 综合 > 正文

wait和notify实例

2013年08月22日 ⁄ 综合 ⁄ 共 1947字 ⁄ 字号 评论关闭

wait和notify必须对同一对象操作才能够起到作用。

 

代码1:

  1. package waitnotify1;
  2. public class ThreadInstance implements Runnable{
  3.     public void run() {
  4.         
  5.         double d = 0;
  6.         
  7.         synchronized(this){
  8.             
  9.             try {
  10.                 
  11.                 Thread.sleep(5000);
  12.                 
  13.             } catch (InterruptedException e) {
  14.                 
  15.                 e.printStackTrace();
  16.                 
  17.             }
  18.             
  19.             for(int i = 0; i < 1000; i++){
  20.                 
  21.                 d += i;
  22.                 
  23.             }
  24.             
  25.             System.out.println(d);
  26.             
  27.             notify();
  28.             
  29.             //假如还有一下sleep代码,那么即便是调用了notify,对方也不会立即从wait中回复,
  30.             //因为该synchronized还没有运行完毕,毕竟它使用的还是wait调用的那个对象。
  31. /*          try {
  32.                 
  33.                 Thread.sleep(5000);
  34.                 
  35.             } catch (InterruptedException e) {
  36.                 
  37.                 e.printStackTrace();
  38.                 
  39.             }*/
  40.             
  41.         }
  42.     }
  43. }

好了,我们对上面的例子进行一下测试:

 

  1. package waitnotify1;
  2. public class TestWaitNotify{
  3.     
  4.     public static void main(String[] args) {
  5.         
  6.         ThreadInstance ti = new ThreadInstance();
  7.         
  8.         Thread t = new Thread(ti);
  9.         
  10.         t.start();
  11.         
  12.         synchronized(t){
  13.             
  14.             try{
  15.                 
  16.                 System.out.println("等待中...");
  17.                 
  18.                 t.wait();
  19.                 
  20.                 System.out.println("它们运行完毕,不必等待了。");
  21.                 
  22.             }catch(Exception e){
  23.                 
  24.                 e.printStackTrace();
  25.                 
  26.             }
  27.             
  28.         }
  29.     }
  30. }

 

我们运行上面的测试用例,得到一下测试结果:

---------------------------------------------------------------------------------------------------------------

等待中...                       (注意在此行打印完毕后并不是立刻打印下面的语句,而是等待用例程序中线程休眠时间结束会才打印
499500.0
它们运行完毕,不必等待了。
---------------------------------------------------------------------------------------------------------------

 

 

抱歉!评论已关闭.