yield(),sleep()以及wait()的區別

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()時不會釋放當前線程所取得的“鎖標誌”,這樣很容易造成“死鎖”。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章