日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

線程基礎

系統 1767 0

線程不是進程

作為有一定開發經驗的程序員來說,在 java 中實現多線程是一件很容易的事情,你只需要將你的類繼承 Thread 類或者實現 Runnable 接口就可以。 其實線程完全可以理解為一個任務。 可以同時運行多個任務的程序,就成為多線程程序。

然而線程并非進程。 進程包括線程,每一個進程都擁有一套自己的變量,而線程間則共享這套變量。 從而帶來了很多風險,比如最典型的臟數據。這些以后會討論。

線程狀態

java 中,線程被定義成有 6 中狀態:

NEW

至今尚未啟動的線程處于這種狀態。 即剛剛 new 出來的 Thread ,但是還未調用 start ()方法。

RUNNABLE

正在 Java 虛擬機中執行的線程處于這種狀態。 該狀態是調用了 start() 方法后的狀態,出于該狀態的線程不一定是正在運行的,他有線程調度器來決定是否運行。

BLOCKED

受阻塞并等待某個監視器鎖的線程處于這種狀態。 阻塞與等待不同,阻塞通常是得不到所需要的資源而被迫停下來等待。

WAITING

無限期地等待另一個線程來執行某一特定操作的線程處于這種狀態。

TIMED_WAITING

等待另一個線程來執行取決于指定等待時間的操作的線程處于這種狀態。

TERMINATED

已退出的線程處于這種狀態。有兩種情況會讓線程退出,其一是 run 方法中的任務執行完成,其二是線程執行時出現異常。

java 的線程狀態只有如上 6 中,他們以 enum 形式被定義在 Thread.State 中。這里要說一下等待狀態,有很多方式能夠讓線程進入等待狀態,比如調用 join ()方法。

join()

對于這個方法,還是要特別的強調一下。在 api 中的解釋如下: Blocks the current Thread ( Thread.currentThread() ) until the receiver finishes its execution and dies. 翻譯過來就是:阻塞當前線程,然后讓接受者完成任務之后,當前線程才開始繼續執行任務。

但是如果接受者在被調用了 join 方法后,有被調用了 interrupt() 方法,則會拋出 java.lang.InterruptedException 異常。可以參考代碼 ThreadDemo01

?

Java代碼 復制代碼 ? 收藏代碼
  1. <STRONG> package ?cn.edu.heut.zcl; ??
  2. ??
  3. ? ??
  4. ??
  5. public ? class ?ThreadDemo01?{ ??
  6. ??
  7. ? ??
  8. ??
  9. ????????? public ? static ? void ?main(String[]?args)?{ ??
  10. ??
  11. ???????????????????TA?ta?=? new ?TA(); ??
  12. ??
  13. ???????????????????ta.start(); ??
  14. ??
  15. ??????????????????? try ?{ ??
  16. ??
  17. ????????????????????????????ta.join(); ??
  18. ??
  19. ???????????????????}? catch ?(InterruptedException?e)?{ ??
  20. ??
  21. ????????????????????????????e.printStackTrace(); ??
  22. ??
  23. ???????????????????} ??
  24. ??
  25. ??????????????????? int ?i?=? 0 ; ??
  26. ??
  27. ??????????????????? while ?((i++)?<? 10 )?{ ??
  28. ??
  29. ????????????????????????????System.out.println( "-------" ); ??
  30. ??
  31. ???????????????????????????? try ?{ ??
  32. ??
  33. ?????????????????????????????????????Thread.sleep( 100 ); ??
  34. ??
  35. ????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  36. ??
  37. ?????????????????????????????????????e.printStackTrace(); ??
  38. ??
  39. ????????????????????????????} ??
  40. ??
  41. ???????????????????} ??
  42. ??
  43. ?????????} ??
  44. ??
  45. } ??
  46. ??
  47. class ?TA? extends ?Thread?{ ??
  48. ??
  49. ? ??
  50. ??
  51. ????????? @Override ??
  52. ??
  53. ????????? public ? void ?run()?{ ??
  54. ??
  55. ??????????????????? super .run(); ??
  56. ??
  57. ??????????????????? int ?i?=? 0 ; ??
  58. ??
  59. ??????????????????? while ?((i++)?<? 40 )?{ ??
  60. ??
  61. ????????????????????????????System.out.println( "---->A" ); ??
  62. ??
  63. ???????????????????????????? if ?(i?==? 10 )?{ ??
  64. ??
  65. ?????????????????????????????????????Thread.currentThread().interrupt(); ??
  66. ??
  67. ????????????????????????????} ??
  68. ??
  69. ??
  70. ???????????????????????????? try ?{ ??
  71. ??
  72. ?????????????????????????????????????Thread.sleep( 100 ); ??
  73. ??
  74. ????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  75. ??
  76. ????????????????????????????????????? //?TODO?Auto-generated?catch?block ??
  77. ??
  78. ?????????????????????????????????????e.printStackTrace(); ??
  79. ??
  80. ????????????????????????????} ??
  81. ??
  82. ???????????????????} ??
  83. ??
  84. ?????????} ??
  85. ??
  86. } ??
  87. </STRONG>??
    
      package cn.edu.heut.zcl;

 

public class ThreadDemo01 {

 

         public static void main(String[] args) {

                   TA ta = new TA();

                   ta.start();

                   try {

                            ta.join();

                   } catch (InterruptedException e) {

                            e.printStackTrace();

                   }

                   int i = 0;

                   while ((i++) < 10) {

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

                            try {

                                     Thread.sleep(100);

                            } catch (InterruptedException e) {

                                     e.printStackTrace();

                            }

                   }

         }

}

class TA extends Thread {

 

         @Override

         public void run() {

                   super.run();

                   int i = 0;

                   while ((i++) < 40) {

                            System.out.println("---->A");

                            if (i == 10) {

                                     Thread.currentThread().interrupt();

                            }


                            try {

                                     Thread.sleep(100);

                            } catch (InterruptedException e) {

                                     // TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                   }

         }

}

    
  


?

?

?

?

記住: join() 方法是將當前線程阻塞

interrupt() 與中斷線程

開發時常常需要用到中斷線程,在早期的 java 版本中,有 stop() 等方法用來控制線程生死,當時這些方法現在已經廢棄,具體愿意以后會談,同時亦可以參考 sun 的一片文章《 Why Are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? 》網址如下:

http://download.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html

當然, jdk 還是為我們提供了強化終止線程的方法。然而, interrupt 方法只是可以用來請求終止線程。當對一個線程調用 interrupt 方法之后,線程的中斷狀態將被置位。每一個線程都具有一個 中斷狀態 ,他是一個 boolean 標志。在實現自己的線程時,應該實時檢查該標志,以判斷線程是否被中斷。

可以通過 Thread.currentThread() 方法得到當前線程,然后通過 is isInterrupted() 方法,來查看中斷狀態。通常如下實現:

while (!Thread.currentThread().isInterrupted() && 。。。 ) {}

如果你已經運行了 ThreadDemo01 代碼,那么你會發現,在 TA 類中如下代碼處:

Java代碼 復制代碼 ? 收藏代碼
  1. if ?(i?==? 10 )?{ ??
  2. ??
  3. ?????????????????????????????????????Thread.currentThread().interrupt(); ??
  4. ??
  5. ????????????????????????????}??
    if (i == 10) {

                                     Thread.currentThread().interrupt();

                            }


  

?

?

?

?

將會拋出異常 java.lang.InterruptedException 。這個是由于在 TA 線程中調用了 interrupt 方法后,中斷狀態已經置為,如果此時再調用 sleep 等阻塞方法后, 該線程不會休眠,想法,他將拋出中斷異常并且將中斷狀態清楚。 所以如下代碼是不會讓線程 TB 停止。 CopyOfThreadDemo02

?

Java代碼 復制代碼 ? 收藏代碼
  1. package ?cn.edu.heut.zcl; ??
  2. ??
  3. ? ??
  4. ??
  5. public ? class ?CopyOfThreadDemo02?{ ??
  6. ??
  7. ? ??
  8. ??
  9. ????????? public ? static ? void ?main(String[]?args)?{ ??
  10. ??
  11. ???????????????????TB?ta?=? new ?TB(); ??
  12. ??
  13. ???????????????????ta.start(); ??
  14. ??
  15. ??????????????????? int ?i?=? 0 ; ??
  16. ??
  17. ??????????????????? while ?((i++)?<? 10 )?{ ??
  18. ??
  19. ????????????????????????????System.out.println( "-------" ); ??
  20. ??
  21. ???????????????????????????? try ?{ ??
  22. ??
  23. ?????????????????????????????????????Thread.sleep( 100 ); ??
  24. ??
  25. ????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  26. ??
  27. ?????????????????????????????????????e.printStackTrace(); ??
  28. ??
  29. ????????????????????????????} ??
  30. ??
  31. ???????????????????} ??
  32. ??
  33. ?????????} ??
  34. ??
  35. } ??
  36. ??
  37. ? ??
  38. ??
  39. class ?TB? extends ?Thread?{ ??
  40. ??
  41. ? ??
  42. ??
  43. ????????? @Override ??
  44. ??
  45. ????????? public ? void ?run()?{ ??
  46. ??
  47. ??????????????????? super .run(); ??
  48. ??
  49. ??????????????????? int ?i?=? 0 ; ??
  50. ??
  51. ??????????????????? while ?(!Thread.currentThread().isInterrupted()?&&?(i++)?<? 40 )?{ ??
  52. ??
  53. ????????????????????????????System.out.println( "---->A" ); ??
  54. ??
  55. ???????????????????????????? if (i?==? 4 )?Thread.currentThread().interrupt(); //在sleep之前調用,將不能終止線程 ??
  56. ??
  57. ???????????????????????????? try ?{ ??
  58. ??
  59. ?????????????????????????????????????Thread.sleep( 100 ); ??
  60. ??
  61. ????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  62. ??
  63. ????????????????????????????????????? //?TODO?Auto-generated?catch?block ??
  64. ??
  65. ?????????????????????????????????????e.printStackTrace(); ??
  66. ??
  67. ????????????????????????????} ??
  68. ??
  69. ???????????????????????????? //if(i?==?4)?Thread.currentThread().interrupt();//在sleep之后調用,將能終止線程 ??
  70. ??
  71. ???????????????????} ??
  72. ??
  73. ?????????} ??
  74. ??
  75. }??
    package cn.edu.heut.zcl;

 

public class CopyOfThreadDemo02 {

 

         public static void main(String[] args) {

                   TB ta = new TB();

                   ta.start();

                   int i = 0;

                   while ((i++) < 10) {

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

                            try {

                                     Thread.sleep(100);

                            } catch (InterruptedException e) {

                                     e.printStackTrace();

                            }

                   }

         }

}

 

class TB extends Thread {

 

         @Override

         public void run() {

                   super.run();

                   int i = 0;

                   while (!Thread.currentThread().isInterrupted() && (i++) < 40) {

                            System.out.println("---->A");

                            if(i == 4) Thread.currentThread().interrupt();//在sleep之前調用,將不能終止線程

                            try {

                                     Thread.sleep(100);

                            } catch (InterruptedException e) {

                                     // TODO Auto-generated catch block

                                     e.printStackTrace();

                            }

                            //if(i == 4) Thread.currentThread().interrupt();//在sleep之后調用,將能終止線程

                   }

         }

}

  

?

?

?

?

你可以自己試一試,運行如上代碼,不能中斷 TB 線程。但是如果在 sleep 之后調用 interrupt ,則會中斷線程。

interrupted() isInterrupted ()

這兩個方法看上去很像,作用也相似可以通過下表來比較兩種異同。

?

是否是 static

返回值

不同

interrupted

當前的中斷狀態

調用后改變中斷狀態

isInterrupted

不改變

?

線程屬性 ---- 線程優先級

?

談優先級可能并不陌生,在 java 中,每一個線程都有一個優先級。默認情況下, 一個線程的優先級直接繼承自他的父類。 sun java 的優先級分成 10 級, 1 表示最小優先級, 10 表示最高優先級。同時 jdk 中還定義了 3 個常量 MIN_PRIORITY(1 ) MAX_PRIORITY(10 ) NORM_PRIORITY(5 )

線程的優先級是依賴與平臺的, windows 中有 7 個優先級。而在 Linux 中, java 虛擬機將線程的優先級忽略,即所有線程的優先級都一樣。 所以在編寫程序是,盡量不要依賴于優先級。

setPriority() 方法,顧名思義就是設置優先級的。

yield ()

yield 的中文意思是:屈服。其實理解成讓步更加準確。調用該方法,將導致當前執行線程出于讓步狀態。如果此時有其他線程一起來搶奪 cpu 資源,那么只要這個搶奪的線程的優先級不低于調用線程。則搶奪線程將會被調用。

線程屬性 ---- 守護線程

守護線程的用途就是為其他線程提供服務。當被服務者死亡后,其也就沒有存在的價值,也就跟著去死了。設置守護線程很簡單:

setDaemon true

只需一步,輕松搞定。在使用守護線程時需要記住,永遠不要去訪問固有資源,如文件、數據庫等。以為你不知道什么時候守護線程會結束。

可以參考 DeamonDemo

?

?

Java代碼 復制代碼 ? 收藏代碼
  1. package ?cn.edu.heut.zcl; ??
  2. ??
  3. /** ?
  4. ?
  5. ?*?演示守護線程 ?
  6. ?
  7. ?*?@author?Legend ?
  8. ?
  9. ?* ?
  10. ?
  11. ?*/ ??
  12. ??
  13. public ? class ?DeamonDemo?{ ??
  14. ??
  15. ????????? ??
  16. ??
  17. ????????? public ? static ? void ?main(String[]?args){ ??
  18. ??
  19. ???????????????????DemonRunnable?dr?=? new ?DemonRunnable(); ??
  20. ??
  21. ???????????????????dr.setDaemon( true ); //設置為守護線程 ??
  22. ??
  23. ???????????????????dr.start(); ??
  24. ??
  25. ??????????????????? int ?i?=? 0 ?; ??
  26. ??
  27. ??????????????????? while ((i++)< 10 ){ ??
  28. ??
  29. ???????????????????????????? try ?{ ??
  30. ??
  31. ?????????????????????????????????????Thread.sleep( 500 ); ??
  32. ??
  33. ?????????????????????????????????????System.out.println(i); ??
  34. ??
  35. ????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  36. ??
  37. ?????????????????????????????????????e.printStackTrace(); ??
  38. ??
  39. ????????????????????????????} ??
  40. ??
  41. ???????????????????} ??
  42. ??
  43. ?????????} ??
  44. ??
  45. ????????? ??
  46. ??
  47. ????????? private ? static ? class ?DemonRunnable? extends ?Thread{ ??
  48. ??
  49. ??????????????????? @Override ??
  50. ??
  51. ??????????????????? public ? void ?run()?{ ??
  52. ??
  53. ???????????????????????????? super .run(); ??
  54. ??
  55. ???????????????????????????? while ( true ){ ??
  56. ??
  57. ?????????????????????????????????????System.out.println( "------" ); ??
  58. ??
  59. ????????????????????????????????????? try ?{ ??
  60. ??
  61. ???????????????????????????????????????????????Thread.sleep( 100 ); ??
  62. ??
  63. ?????????????????????????????????????}? catch ?(InterruptedException?e)?{ ??
  64. ??
  65. ???????????????????????????????????????????????e.printStackTrace(); ??
  66. ??
  67. ?????????????????????????????????????} ??
  68. ??
  69. ????????????????????????????} ??
  70. ??
  71. ???????????????????} ??
  72. ??
  73. ?????????} ??
  74. ??
  75. }??

?

?

?來自: http://www.iteye.com/topic/954765

線程基礎


更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 武胜县| 阿鲁科尔沁旗| 天门市| 阿拉善盟| 堆龙德庆县| 陈巴尔虎旗| 广宁县| 内乡县| 赣榆县| 柯坪县| 大理市| 湖州市| 视频| 汝城县| 九台市| 武胜县| 唐山市| 钟祥市| 互助| 敦化市| 万山特区| 平顺县| 柘荣县| 固始县| 永寿县| 时尚| 景谷| 历史| 太白县| 班戈县| 三穗县| 云阳县| 衡东县| 萍乡市| 哈巴河县| 英吉沙县| 阳谷县| 怀仁县| 平舆县| 绍兴市| 浦县|