閱讀339 返回首頁    go 阿裏雲 go 技術社區[雲棲]


java線程技術——線程的創建運行終止

https://blog.chinaunix.net/uid-122937-id-192835.html

1.創建和運行線程
在Java中,多線程的實現有兩種方式:
      擴展java.lang.Thread類
      實現java.lang.Runnable接口

(1)擴展Thread類
      Thread Test = new Thread();
      Test.start();

(2)實現Runnable接口
將實現Runnable接口的類實例化      
      Test impelements Runnable;//繼承接口,實現run()
 建立一個Thread對象,並將第一步實例化後的對象作為參數傳入Thread類的構造方法。
      Test t = new Test();
      Thread test = new Thread(t);
最後通過Thread類的start方法建立線程。
      test.start();

建議使用runable實現java多線程,不管如何,最終都需要通過thread.start()來使線程處於可運行狀態。

2.例:顯示線程名稱

  1. /**
  2.  * 運行二個線程,顯示線程的默認名稱.
  3.  * @version V1.0 ,2011-3-24
  4.  * @author xiahui
  5.  */
  6. public class DispTheadName extends Thread {
  7.     public void run() {
  8.         System.out.println(this.getName());
  9.     }
  10.     public static void main(String[] args) {
  11.         System.out.println(Thread.currentThread().getName());
  12.         DispTheadName thread1 = new DispTheadName();
  13.         DispTheadName thread2 = new DispTheadName();
  14.         thread1.start();
  15.         thread2.start();
  16.     }
  17. }
顯示結果
  1. main
  2. Thread-1
  3. Thread-0
main是主線程的名子,Thread-1和Thread-2分別是thread1和thread2的輸出結果。

3.例:修改線程名稱
  1. /**
  2.  * 修改線程的名稱
  3.  * @version V1.0 ,2011-3-24
  4.  * @author xiahui
  5.  */
  6. public class ChangeTheadName extends Thread {
  7.     private String who;

  8.     public void run() {
  9.         System.out.println(who + ":" + this.getName());
  10.     }
  11.     public ChangeTheadName(String who) {
  12.         super();
  13.         this.who = who;
  14.     }
  15.     public ChangeTheadName(String who, String name) {
  16.         super(name);
  17.         this.who = who;
  18.     }
  19.     public static void main(String[] args) {
  20.         ChangeTheadName thread1 = new ChangeTheadName("thread1", "MyThread1");//初始化線程名稱
  21.         ChangeTheadName thread2 = new ChangeTheadName("thread2");
  22.         ChangeTheadName thread3 = new ChangeTheadName("thread3");
  23.         thread2.setName("MyThread2");//調用線程類的setName()修改名稱
  24.         thread1.start();
  25.         thread2.start();
  26.         thread3.start();
  27.     }
  28. }
運行結果
  1. thread2:MyThread2
  2. thread1:MyThread1
  3. thread3:Thread-1
注意:
      在調用start方法前後都可以使用setName設置線程名,但在調用start方法後使用setName修改線程名,會產生不確定性,也就是說可能在 run方法執行完後才會執行setName.如果在run方法中要使用線程名,就會出現雖然調用了setName方法,但線程名卻未修改的現象。

      Thread類的start方法不能多次調用,如不能調用兩次thread1.start()方法。否則會拋出一個IllegalThreadStateException異常。

4.通過Runnable接口來創建線程
  1. /**
  2.  * create thread by Runnable Interface
  3.  * @version V1.0 ,2011-3-27 
  4.  * @author xiahui
  5.  */
  6. public class RunnableClass implements Runnable
  7. {
  8.     public void run()
  9.     {
  10.         System.out.println(Thread.currentThread().getName());
  11.     }
  12.     public static void main(String[] args)
  13.     {
  14.         RunnableClass t1 = new RunnableClass();
  15.         RunnableClass t2 = new RunnableClass();
  16.         Thread thread1 = new Thread(t1, "MyThread1");
  17.         Thread thread2 = new Thread(t2);
  18.         thread2.setName("MyThread2");
  19.         thread1.start();
  20.         thread2.start();
  21.     }
  22. }
運行結果
  1. MyThread1
  2. MyThread2

5.線程的運行

      線程在建立後並不馬上執行run方法中的代碼,而是處於等待狀態。線程處於等待狀態時,可以通過Thread類的方法來設置線程不各種屬性,如線程的優先級(setPriority)、線程名(setName)和線程的類型(setDaemon)等。
      當調用start方法後,線程開始執行run( )中的代碼。線程進入運行狀態。可以通過Thread類的isAlive方法來判斷線程是否處於運行狀態。
      當線程處於運行狀態時,isAlive返回true,當isAlive返回false時,可能線程處於等待狀態,也可能處於停止狀態。

6 例:線程的創建、運行和停止
  1. /**
  2.  * 線程的創建、運行和停止.
  3.  * @version V1.0 ,2011-3-27 
  4.  * @author xiahui
  5.  */
  6. public class TheadState extends Thread
  7. {
  8.     public void run()
  9.     {
  10.         int n = 0;
  11.         while (( n) < 1000); 
  12.     }
  13.      
  14.     public static void main(String[] args) throws Exception
  15.     {
  16.         TheadState thread1 = new TheadState();
  17.         System.out.println("isAlive: " thread1.isAlive());
  18.         thread1.start();
  19.         System.out.println("isAlive: " thread1.isAlive());
  20.         thread1.join(); // 等線程thread1結束後再繼續執行 
  21.         System.out.println("thread1已經結束!");
  22.         System.out.println("isAlive: " thread1.isAlive());
  23.     }
  24. }
運行結果
  1. isAlive: false
  2. isAlive: true
  3. thread1已經結束!
  4. isAlive: false
7.終止線程
    有三種方法可以使終止線程
    1.  使用退出標誌,使線程正常退出,也就是當run方法完成後線程終止。
    2.  使用stop方法強行終止線程(這個方法不推薦使用,因為stop和suspend、resume一樣,就象突然關閉計算機電源,而不是按正常程序關機一樣,可能會產生不可預料的結果)。
    3.  使用interrupt方法中斷線程。
         使用interrupt方法來終端線程可分為兩種情況:
        (1)線程處於阻塞狀態,如使用了sleep方法。
        (2)使用while(!isInterrupted()){……}來判斷線程是否被中斷。
        在第一種情況下使用interrupt方法,sleep方法將拋出一個InterruptedException例外,而在第二種情況下線程將直接退出

8. 例:通過退出標誌終止線程
  1. /**
  2.  * 通過退出標誌終止線程.
  3.  * @version V1.0 ,2011-3-29 
  4.  * @author xiahui
  5.  */
  6. public class ThreadFlag extends Thread
  7. {
  8.     public volatile boolean exit = false;

  9.     public void run()
  10.     {
  11.         while (!exit)
  12.             System.out.println("運行!");
  13.     }
  14.     public static void main(String[] args) throws Exception
  15.     {
  16.         ThreadFlag thread = new ThreadFlag();
  17.         thread.start();
  18.         sleep(100); // 主線程延遲
  19.         thread.exit = true; // 終止線程thread
  20.         System.out.println("線程退出!");
  21.     }
  22. }
運行結果必定為
  1. 運行!
  2. 運行!
  3. 運行!
  4. 運行!
  5. 運行!
  6. 線程退出!

參考文獻
1.java線程指南. https://java.chinaitlab.com/Special/javaline/Index.html
2.線程的生命周期. https://java.chinaitlab.com/line/778850_2.html
3.Java Thread suspend Example. https://www.codingdiary.com/developers/developers/diary/javaapi/java/lang/SampleCode/suspendExampleCode.html

最後更新:2017-04-03 18:52:12

  上一篇:go 第十一章 Hibernate的查詢 本地SQL查詢
  下一篇:go 第十一章 Hibernate的查詢 HQL麵向對象的查詢語言