`
yydcj
  • 浏览: 59973 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

彻底明白多线程通信机制

阅读更多

引自http://blog.csdn.net/java2000_net/archive/2008/06/15/2551072.aspx

 

java中yield(),sleep()以及wait()的区别(修正版) http://qdisb.blogbus.com/logs/223774.html 原文有多处代码错误,这里进行了修正 --------------------------------------------------------------

往往混淆了这三个函数的使用。

从操作系统的角度讲,os会维护一个ready queue(就绪的线程队列)。并且在某一时刻cpu只为ready queue中位于队列头部的线程服务。 但是当前正在被服务的线程可能觉得cpu的服务质量不够好,于是提前退出,这就是yield。 或者当前正在被服务的线程需要睡一会,醒来后继续被服务,这就是sleep。 

sleep方法不推荐使用,可用wait。 线程退出最好自己实现,在运行状态中一直检验一个状态,如果这个状态为真,就一直运行,如果外界更改了这个状态变量,那么线程就停止运行。

sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。 sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。

当调用wait()后,线程会释放掉它所占有的“锁标志”,从而使线程所在对象中的其它synchronized数据可被别的线程使用。

waite()和notify()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized  block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运 行时会发生IllegalMonitorStateException的异常。

彻底明白多线程通信机制:

线程间的通信 1.    线程的几种状态 线程有四种状态,任何一个线程肯定处于这四种状态中的一种:

1)    产生(New):线程对象已经产生,但尚未被启动,所以无法执行。如通过new产生了一个线程对象后没对它调用start()函数之前。

2)    可执行(Runnable):每个支持多线程的系统都有一个排程器,排程器会从线程池中选择一个线程并启动它。当一个线程处于可执行状态时,表示它可能正 处于线程池中等待排排程器启动它;也可能它已正在执行。如执行了一个线程对象的start()方法后,线程就处于可执行状态,但显而易见的是此时线程不一 定正在执行中。

3)    死亡(Dead):当一个线程正常结束,它便处于死亡状态。如一个线程的run()函数执行完毕后线程就进入死亡状态。 4)    停滞(Blocked):当一个线程处于停滞状态时,系统排程器就会忽略它,不对它进行排程。当处于停滞状态的线程重新回到可执行状态时,它有可能重新执 行。如通过对一个线程调用wait()函数后,线程就进入停滞状态,只有当再次对该线程调用notify或notifyAll后它才能再次回到可执行状 态。

2.    class Thread下的常用函数函数 2.1    suspend()、resume() 1)    通过suspend()函数,可使线程进入停滞状态。通过suspend()使线程进入停滞状态后,除非收到resume()消息,否则该线程不会变回可执行状态。 2)    当调用suspend()函数后,线程不会释放它的“锁标志”。 例11: 

  1.    
  2.   
  3. public   class  MyTest {  
  4.   
  5.   public   static   void  main(String[] args) {  
  6.   
  7.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  8.   
  9.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  10.   
  11.     t1.start();// (5)   
  12.   
  13.     // t1.start(); //(3)   
  14.   
  15.     t2.start();// (4)   
  16.   
  17.   }  
  18.   
  19. }  
  20.   
  21. class  TestThreadMethod  extends  Thread {  
  22.   
  23.   public   static   int  shareVar =  0 ;  
  24.   
  25.   public  TestThreadMethod(String name) {  
  26.   
  27.     super (name);  
  28.   
  29.   }  
  30.   
  31.   public   synchronized   void  run() {  
  32.   
  33.     if  (shareVar ==  0 ) {  
  34.   
  35.       for  ( int  i =  0 ; i <  5 ; i++) {  
  36.   
  37.         shareVar++;  
  38.   
  39.         if  (shareVar ==  5 ) {  
  40.   
  41.           this .suspend(); // (1)   
  42.   
  43.         }  
  44.   
  45.       }  
  46.   
  47.     } else  {  
  48.   
  49.       System.out.print(Thread.currentThread().getName());  
  50.   
  51.       System.out.println(" shareVar = "  + shareVar);  
  52.   
  53.       this .resume(); // (2)   
  54.   
  55.     }  
  56.   
  57.   }  
  58.   
  59. }  
 

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    t1.start();// (5)

    // t1.start(); //(3)

    t2.start();// (4)

  }

}

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public synchronized void run() {

    if (shareVar == 0) {

      for (int i = 0; i < 5; i++) {

        shareVar++;

        if (shareVar == 5) {

          this.suspend();// (1)

        }

      }

    } else {

      System.out.print(Thread.currentThread().getName());

      System.out.println(" shareVar = " + shareVar);

      this.resume();// (2)

    }

  }

}

运行结果为:

t2 shareVar = 5 i.    当代码(5)的t1所产生的线程运行到代码(1)处时,该线程进入停滞状态。然后排程器从线程池中唤起代码(4)的t2所产生的线程,此时 shareVar值不为0,所以执行else中的语句。 ii.    也许你会问,那执行代码(2)后为什么不会使t1进入可执行状态呢?正如前面所说,t1和t2是两个不同对象的线程,而代码(1)和(2)都只对当前对象 进行操作,所以t1所产生的线程执行代码(1)的结果是对象t1的当前线程进入停滞状态;而t2所产生的线程执行代码(2)的结果是把对象t2中的所有处 于停滞状态的线程调回到可执行状态。 iii.    那现在把代码(4)注释掉,并去掉代码(3)的注释,是不是就能使t1重新回到可执行状态呢?运行结果是什么也不输出。为什么会这样呢?也许你会认为,当 代码(5)所产生的线程执行到代码(1)时,它进入停滞状态;而代码(3)所产生的线程和代码(5)所产生的线程是属于同一个对象的,那么就当代码(3) 所产生的线程执行到代码(2)时,就可使代码(5)所产生的线程执行回到可执行状态。但是要清楚,suspend()函数只是让当前线程进入停滞状态,但 并不释放当前线程所获得的“锁标志”。所以当代码(5)所产生的线程进入停滞状态时,代码(3)所产生的线程仍不能启动,因为当前对象的“锁标志”仍被代 码(5)所产生的线程占有。

2.2     sleep() 1)    sleep ()函数有一个参数,通过参数可使线程在指定的时间内进入停滞状态,当指定的时间过后,线程则自动进入可执行状态。 2)    当调用sleep ()函数后,线程不会释放它的“锁标志”。 例12:

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   synchronized   void  run() {  
  14.   
  15.     for  ( int  i =  0 ; i <  3 ; i++) {  
  16.   
  17.       System.out.print(Thread.currentThread().getName());  
  18.   
  19.       System.out.println(" : "  + i);  
  20.   
  21.       try  {  
  22.   
  23.         Thread.sleep(100 ); // (4)   
  24.   
  25.       } catch  (InterruptedException e) {  
  26.   
  27.         System.out.println("Interrupted" );  
  28.   
  29.       }  
  30.   
  31.     }  
  32.   
  33.   }  
  34.   
  35. }  
  36.   
  37. public   class  MyTest {  
  38.   
  39.   public   static   void  main(String[] args) {  
  40.   
  41.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  42.   
  43.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  44.   
  45.     t1.start(); // (1)   
  46.   
  47.     t1.start(); // (2)   
  48.   
  49.     // new Thread(t1).start();// (4)   
  50.   
  51.     // new Thread(t1).start();// (5)   
  52.   
  53.     // new Thread(t2).start(); (3)t2.start();   
  54.   
  55.   }  
  56.   
  57. }  
 

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public synchronized void run() {

    for (int i = 0; i < 3; i++) {

      System.out.print(Thread.currentThread().getName());

      System.out.println(" : " + i);

      try {

        Thread.sleep(100);// (4)

      } catch (InterruptedException e) {

        System.out.println("Interrupted");

      }

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    t1.start(); // (1)

    t1.start(); // (2)

    // new Thread(t1).start();// (4)

    // new Thread(t1).start();// (5)

    // new Thread(t2).start(); (3)t2.start();

  }

}

运行结果为:

引用: Exception in thread "main" java.lang.IllegalThreadStateException t1 : 0  at java.lang.Thread.start(Unknown Source)  at MyTest.main(MyTest.java:26) t1 : 1 t1 : 2

可见,对于同一个对象直接启动2次会出现异常 我们将(1)和(2)注释掉,改成 (4)和(5)的代码,则运行结果为:

引用: Thread-0 : 0 Thread-0 : 1 Thread-0 : 2 Thread-1 : 0 Thread-1 : 1 Thread-1 : 2

由结果可证明,虽然在run()中执行了sleep(),但是它不会释放对象的“锁标志”,所以除非代码(1)的线程执行完run()函数并释放对象的“锁标志”,否则代码(2)的线程永远不会执行。

如果把代码(2)注释掉,并去掉代码(3)的注释,结果将变为:

引用: Thread-0 : 0 Thread-1 : 0 Thread-0 : 1 Thread-1 : 1 Thread-1 : 2 Thread-0 : 2

由于t1和t2是两个对象的线程,所以当线程t1通过sleep()进入停滞时,排程器会从线程池中调用其它的可执行线程,从而t2线程被启动。

例13:

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   synchronized   void  run() {  
  14.   
  15.     for  ( int  i =  0 ; i <  5 ; i++) {  
  16.   
  17.       System.out.print(Thread.currentThread().getName());  
  18.   
  19.       System.out.println(" : "  + i);  
  20.   
  21.       try  {  
  22.   
  23.         if  (Thread.currentThread().getName().equals( "t1" ))  
  24.   
  25.           Thread.sleep(200 );  
  26.   
  27.         else   
  28.   
  29.           Thread.sleep(100 );  
  30.   
  31.       } catch  (InterruptedException e) {  
  32.   
  33.         System.out.println("Interrupted" );  
  34.   
  35.       }  
  36.   
  37.     }  
  38.   
  39.   }  
  40.   
  41. }  
  42.   
  43. public   class  MyTest {  
  44.   
  45.   public   static   void  main(String[] args) {  
  46.   
  47.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  48.   
  49.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  50.   
  51.     t1.start();  
  52.   
  53.     // t1.start();   
  54.   
  55.     t2.start();  
  56.   
  57.   }  
  58.   
  59. }  
 

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public synchronized void run() {

    for (int i = 0; i < 5; i++) {

      System.out.print(Thread.currentThread().getName());

      System.out.println(" : " + i);

      try {

        if (Thread.currentThread().getName().equals("t1"))

          Thread.sleep(200);

        else

          Thread.sleep(100);

      } catch (InterruptedException e) {

        System.out.println("Interrupted");

      }

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    t1.start();

    // t1.start();

    t2.start();

  }

}

运行结果为:

引用: t1 : 0 t2 : 0 t2 : 1 t1 : 1 t2 : 2 t2 : 3 t1 : 2 t2 : 4 t1 : 3 t1 : 4

由于线程t1调用了sleep(200),而线程t2调用了sleep(100),所以线程t2处于停滞状态的时间是线程t1的一半,从从结果反映出来的就是线程t2打印两倍次线程t1才打印一次。

2.3    yield() 1)    通过yield ()函数,可使线程进入可执行状态,排程器从可执行状态的线程中重新进行排程。所以调用了yield()的函数也有可能马上被执行。 2)    当调用yield ()函数后,线程不会释放它的“锁标志”。 例14:

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   synchronized   void  run() {  
  14.   
  15.     for  ( int  i =  0 ; i <  4 ; i++) {  
  16.   
  17.       System.out.println(Thread.currentThread().getName() + " : "  + i);  
  18.   
  19.       Thread.yield();  
  20.   
  21.     }  
  22.   
  23.   }  
  24.   
  25. }  
  26.   
  27. public   class  MyTest {  
  28.   
  29.   public   static   void  main(String[] args) {  
  30.   
  31.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  32.   
  33.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  34.   
  35.     new  Thread(t1).start();  
  36.   
  37.     new  Thread(t1).start(); // (1)   
  38.   
  39.     // new Thread(t2).start(); //(2)   
  40.   
  41.   }  
  42.   
  43. }  
 

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public synchronized void run() {

    for (int i = 0; i < 4; i++) {

      System.out.println(Thread.currentThread().getName() + " : " + i);

      Thread.yield();

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    new Thread(t1).start();

    new Thread(t1).start();// (1)

    // new Thread(t2).start(); //(2)

  }

}

运行结果为:

引用: Thread-0 : 0 Thread-0 : 1 Thread-0 : 2 Thread-0 : 3 Thread-1 : 0 Thread-1 : 1 Thread-1 : 2 Thread-1 : 3

从结果可知调用yield()时并不会释放对象的“锁标志”。  如果把代码(1)注释掉,并去掉代码(2)的注释,结果为:

引用: Thread-0 : 0 Thread-1 : 0 Thread-0 : 1 Thread-1 : 1 Thread-0 : 2 Thread-1 : 2 Thread-0 : 3 Thread-1 : 3

从结果可知,虽然t1线程调用了yield(),但它马上又被执行了。 2.4    sleep()和yield()的区别 1)    sleep()使当前线程进入停滞状态,所以执行sleep()的线程在指定的时间内肯定不会执行;yield()只是使当前线程重新回到可执行状态,所以执行yield()的线程有可能在进入到可执行状态后马上又被执行。 2)    sleep()可使优先级低的线程得到执行的机会,当然也可以让同优先级和高优先级的线程有执行的机会;yield()只能使同优先级的线程有执行的机会。 例15:

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   void  run() {  
  14.   
  15.     for  ( int  i =  0 ; i <  4 ; i++) {  
  16.   
  17.       System.out.println(Thread.currentThread().getName() + " : "  + i);  
  18.   
  19.       // Thread.yield(); (1)   
  20.   
  21.       /* (2) */   
  22.   
  23.       try  {  
  24.   
  25.         Thread.sleep(300 );  
  26.   
  27.       } catch  (InterruptedException e) {  
  28.   
  29.         System.out.println("Interrupted" );  
  30.   
  31.       }  
  32.   
  33.     }  
  34.   
  35.   }  
  36.   
  37. }  
  38.   
  39. public   class  MyTest {  
  40.   
  41.   public   static   void  main(String[] args) {  
  42.   
  43.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  44.   
  45.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  46.   
  47.     t1.setPriority(Thread.MAX_PRIORITY);  
  48.   
  49.     t2.setPriority(Thread.MIN_PRIORITY);  
  50.   
  51.     t1.start();  
  52.   
  53.     t2.start();  
  54.   
  55.   }  
  56.   
  57. }  
 

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public void run() {

    for (int i = 0; i < 4; i++) {

      System.out.println(Thread.currentThread().getName() + " : " + i);

      // Thread.yield(); (1)

      /* (2) */

      try {

        Thread.sleep(300);

      } catch (InterruptedException e) {

        System.out.println("Interrupted");

      }

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    t1.setPriority(Thread.MAX_PRIORITY);

    t2.setPriority(Thread.MIN_PRIORITY);

    t1.start();

    t2.start();

  }

}

运行结果为:

引用: t1 : 0 t2 : 0 t1 : 1 t2 : 1 t1 : 2 t2 : 2 t1 : 3 t2 : 3

由结果可见,通过sleep()可使优先级较低的线程有执行的机会。注释掉代码(2),并去掉代码(1)的注释,结果为:

引用: t1 : 0 t1 : 1 t2 : 0 t1 : 2 t1 : 3 t2 : 1 t2 : 2 t2 : 3

可见,调用yield(),不同优先级的线程永远不会得到执行机会。 2.5    join() 使调用join()的线程执行完毕后才能执行其它线程,在一定意义上,它可以实现同步的功能。 例16:

  1.    
  2.   
  3.  class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   void  run() {  
  14.   
  15.     for  ( int  i =  0 ; i <  4 ; i++) {  
  16.   
  17.       System.out.println(" "  + i);  
  18.   
  19.       try  {  
  20.   
  21.         Thread.sleep(300 );  
  22.   
  23.       } catch  (InterruptedException e) {  
  24.   
  25.         System.out.println("Interrupted" );  
  26.   
  27.       }  
  28.   
  29.     }  
  30.   
  31.   }  
  32.   
  33. }  
  34.   
  35. public   class  MyTest {  
  36.   
  37.   public   static   void  main(String[] args) {  
  38.   
  39.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  40.   
  41.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  42.   
  43.     t1.start();  
  44.   
  45.     try  {  
  46.   
  47.       t1.join();  
  48.   
  49.     } catch  (InterruptedException e) {}  
  50.   
  51.     t2.start();  
  52.   
  53.   }  
  54.   
  55. }  
 

 class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public void run() {

    for (int i = 0; i < 4; i++) {

      System.out.println(" " + i);

      try {

        Thread.sleep(300);

      } catch (InterruptedException e) {

        System.out.println("Interrupted");

      }

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    t1.start();

    try {

      t1.join();

    } catch (InterruptedException e) {}

    t2.start();

  }

}

运行结果为:

引用: 0 1 2 3 0 1 2 3

3. class Object下常用的线程函数 wait()、notify()和notifyAll()这三个函数由java.lang.Object类提供,用于协调多个线程对共享数据的存取。

3.1 wait()、notify()和notifyAll()

1) wait()函数有两种形式:第一种形式接受一个毫秒值,用于在指定时间长度内暂停线程,使线程进入停滞状态。第二种形式为不带参数,代表waite()在notify()或notifyAll()之前会持续停滞。

2) 当对一个对象执行notify()时,会从线程等待池中移走该任意一个线程,并把它放到锁标志等待池中;当对一个对象执行notifyAll()时,会从线程等待池中移走所有该对象的所有线程,并把它们放到锁标志等待池中。

3) 当调用wait()后,线程会释放掉它所占有的“锁标志”,从而使线程所在对象中的其它synchronized数据可被别的线程使用。

例17: 下面,我们将对例11中的例子进行修改

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   static   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.   }  
  12.   
  13.   public   synchronized   void  run() {  
  14.   
  15.     if  (shareVar ==  0 ) {  
  16.   
  17.       for  ( int  i =  0 ; i <  10 ; i++) {  
  18.   
  19.         shareVar++;  
  20.   
  21.         if  (shareVar ==  5 ) {  
  22.   
  23.           try  {  
  24.   
  25.             this .wait(); // (4)   
  26.   
  27.           } catch  (InterruptedException e) {}  
  28.   
  29.         }  
  30.   
  31.       }  
  32.   
  33.     }  
  34.   
  35.     if  (shareVar !=  0 ) {  
  36.   
  37.       System.out.print(Thread.currentThread().getName());  
  38.   
  39.       System.out.println(" shareVar = "  + shareVar);  
  40.   
  41.       this .notify(); // (5)   
  42.   
  43.     }  
  44.   
  45.   }  
  46.   
  47. }  
  48.   
  49. public   class  MyTest {  
  50.   
  51.   public   static   void  main(String[] args) {  
  52.   
  53.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  54.   
  55.     TestThreadMethod t2 = new  TestThreadMethod( "t2" );  
  56.   
  57.     new  Thread(t1).start(); // (1)   
  58.   
  59.     // new Thread(t1).start(); // (2)   
  60.   
  61.     new  Thread(t2).start(); // (3)   
  62.   
  63.   }  
  64.   
  65. }  
 

class TestThreadMethod extends Thread {

  public static int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

  }

  public synchronized void run() {

    if (shareVar == 0) {

      for (int i = 0; i < 10; i++) {

        shareVar++;

        if (shareVar == 5) {

          try {

            this.wait();// (4)

          } catch (InterruptedException e) {}

        }

      }

    }

    if (shareVar != 0) {

      System.out.print(Thread.currentThread().getName());

      System.out.println(" shareVar = " + shareVar);

      this.notify();// (5)

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    TestThreadMethod t2 = new TestThreadMethod("t2");

    new Thread(t1).start();// (1)

    // new Thread(t1).start(); // (2)

    new Thread(t2).start();// (3)

  }

}

运行结果为:

引用: Thread-1 shareVar = 5

因为t1和t2是两个不同对象,所以线程t2调用代码(5)不能唤起线程t1。如果去掉代码(2)的注释,并注释掉代码(3),结果为:

引用: Thread-1 shareVar = 5 Thread-0 shareVar = 10

这是因为,当代码(1)的线程执行到代码(4)时,它进入停滞状态,并释放对象的锁状态。接着,代码(2)的线程执行run(),由于此时 shareVar值为5,所以执行打印语句并调用代码(5)使代码(1)的线程进入可执行状态,然后代码(2)的线程结束。当代码(1)的线程重新执行 后,它接着执行for()循环一直到shareVar=10,然后打印shareVar。

3.2 wait()、notify()和synchronized

waite()和notify()因为会对对象的“锁标志”进行操作,所以它们必须在synchronized函数或synchronized  block中进行调用。如果在non-synchronized函数或non-synchronized block中进行调用,虽然能编译通过,但在运 行时会发生IllegalMonitorStateException的异常。

例18:

  1.    
  2.   
  3. class  TestThreadMethod  extends  Thread {  
  4.   
  5.   public   int  shareVar =  0 ;  
  6.   
  7.   public  TestThreadMethod(String name) {  
  8.   
  9.     super (name);  
  10.   
  11.     new  Notifier( this );  
  12.   
  13.   }  
  14.   
  15.   public   synchronized   void  run() {  
  16.   
  17.     if  (shareVar ==  0 ) {  
  18.   
  19.       for  ( int  i =  0 ; i <  5 ; i++) {  
  20.   
  21.         shareVar++;  
  22.   
  23.         System.out.println("i = "  + shareVar);  
  24.   
  25.         try  {  
  26.   
  27.           System.out.println("wait......" );  
  28.   
  29.           this .wait();  
  30.   
  31.         } catch  (InterruptedException e) {}  
  32.   
  33.       }  
  34.   
  35.     }  
  36.   
  37.   }  
  38.   
  39. }  
  40.   
  41. class  Notifier  extends  Thread {  
  42.   
  43.   private  TestThreadMethod ttm;  
  44.   
  45.   Notifier(TestThreadMethod t) {  
  46.   
  47.     ttm = t;  
  48.   
  49.     start();  
  50.   
  51.   }  
  52.   
  53.   public   void  run() {  
  54.   
  55.     while  ( true ) {  
  56.   
  57.       try  {  
  58.   
  59.         sleep(2000 );  
  60.   
  61.       } catch  (InterruptedException e) {}  
  62.   
  63.       /* 1 要同步的不是当前对象的做法 */   
  64.   
  65.       synchronized  (ttm) {  
  66.   
  67.         System.out.println("notify......" );  
  68.   
  69.         ttm.notify();  
  70.   
  71.       }  
  72.   
  73.     }  
  74.   
  75.   }  
  76.   
  77. }  
  78.   
  79. public   class  MyTest {  
  80.   
  81.   public   static   void  main(String[] args) {  
  82.   
  83.     TestThreadMethod t1 = new  TestThreadMethod( "t1" );  
  84.   
  85.     t1.start();  
  86.   
  87.   }  
  88.   
  89. }  
 

class TestThreadMethod extends Thread {

  public int shareVar = 0;

  public TestThreadMethod(String name) {

    super(name);

    new Notifier(this);

  }

  public synchronized void run() {

    if (shareVar == 0) {

      for (int i = 0; i < 5; i++) {

        shareVar++;

        System.out.println("i = " + shareVar);

        try {

          System.out.println("wait......");

          this.wait();

        } catch (InterruptedException e) {}

      }

    }

  }

}

class Notifier extends Thread {

  private TestThreadMethod ttm;

  Notifier(TestThreadMethod t) {

    ttm = t;

    start();

  }

  public void run() {

    while (true) {

      try {

        sleep(2000);

      } catch (InterruptedException e) {}

      /* 1 要同步的不是当前对象的做法 */

      synchronized (ttm) {

        System.out.println("notify......");

        ttm.notify();

      }

    }

  }

}

public class MyTest {

  public static void main(String[] args) {

    TestThreadMethod t1 = new TestThreadMethod("t1");

    t1.start();

  }

}

运行结果为:

引用: i = 1 wait...... notify...... i = 2 wait...... notify...... i = 3 wait...... notify...... i = 4 wait...... notify...... i = 5 wait...... notify...... notify...... notify......

4. wait()、notify()、notifyAll()和suspend()、resume()、sleep()的讨论

4.1 这两组函数的区别

1) wait()使当前线程进入停滞状态时,还会释放当前线程所占有的“锁标志”,从而使线程对象中的synchronized资源可被对象中别的线程使用;而suspend()和sleep()使当前线程进入停滞状态时不会释放当前线程所占有的“锁标志”。

2) 前一组函数必须在synchronized函数或synchronized block中调用,否则在运行时会产生错误;而后一组函数可以non-synchronized函数和synchronized block中调用。

4.2 这两组函数的取舍 Java2已不建议使用后一组函数。因为在调用wait()时不会释放当前线程所取得的“锁标志”,这样很容易造成“死锁”。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics