Java多線程深入理解

来源:https://www.cnblogs.com/chenshengjava/archive/2018/04/10/8776296.html
-Advertisement-
Play Games

在java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable介面。 對於直接繼承Thread的類來說,代碼大致框架是: ? 1 2 3 4 5 6 7 8 9 10 11 class 類名 extends Thread{ 方法1; 方法2; … public voi ...


java中要想實現多線程,有兩種手段,一種是繼續Thread類,另外一種是實現Runable介面。

對於直接繼承Thread的類來說,代碼大致框架是:

?
1 2 3 4 5 6 7 8 9 10 11 class 類名 extends Thread{  方法1 方法2;  …  public void run(){  // other code…  屬性1;  屬性2;  … 

先看一個簡單的例子:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 /**  * @author Hashsound 繼承Thread類,直接調用run方法  * */  class hello extends Thread {          private String name;          public hello() {               public hello(String name) {          this.name = name;               public void run() {          for (int i = 0; i < 5; i++) {              System.out.println(name + "運行 " + i);                        public static void main(String[] args) {          hello h1 = new hello("A");          hello h2 = new hello("B");          h1.run();          h2.run();      

【運行結果】:

複製代碼
A運行     0
A運行     1
A運行     2
A運行     3
A運行     4
B運行     0
B運行     1
B運行     2
B運行     3
B運行     4
複製代碼

我們會發現這些都是順序執行的,說明我們的調用方法不對,應該調用的是start()方法。
當我們把上面的主函數修改為如下所示的時候:

?
1 2 3 4 5 6 public static void main(String[] args) {          hello h1=new hello("A");          hello h2=new hello("B");          h1.start();          h2.start(); 

然後運行程式,輸出的可能的結果如下:

複製代碼
B運行 0
B運行 1
B運行 2
A運行 0
A運行 1
A運行 2
B運行 3
B運行 4
A運行 3
A運行 4
複製代碼

因為需要用到CPU的資源,所以每次的運行結果基本是都不一樣的,呵呵。
註意:雖然我們在這裡調用的是start()方法,但是實際上調用的還是run()方法的主體。
那麼:為什麼我們不能直接調用run()方法呢?
我的理解是:線程的運行需要本地操作系統的支持。
如果你查看start的源代碼的時候,會發現:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 public synchronized void start() {          /**      * This method is not invoked for the main method thread or "system"      * group threads created/set up by the VM. Any new functionality added       * to this method in the future may have to also be added to the VM.      *      * A zero status value corresponds to state "NEW".      */       if (threadStatus != 0 || this != me)              throw new IllegalThreadStateException();          group.add(this);          start0();          if (stopBeforeStart) {          stop0(throwableFromStop);       private native void start0(); 

註意我用紅色加粗的那一條語句,說明此處調用的是start0()。並且這個這個方法用了native關鍵字,次關鍵字表示調用本地操作系統的函數。因為多線程的實現需要本地操作系統的支持。
但是start方法重覆調用的話,會出現java.lang.IllegalThreadStateException異常。
通過實現Runnable介面:
大致框架是:

來先看一個小例子吧:

?
1 2 3 4 5 6 7 8 9 10 11 class 類名 implements Runnable{  方法1 方法2;  …  public void run(){  // other code…  屬性1;  屬性2;  … 
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 /**  * @author Hashsound 實現Runnable介面  * */  class hello implements Runnable {           public hello() {                     public hello(String name) {          this.name = name;                public void run() {          for (int i = 0; i < 5; i++) {              System.out.println(name + "運行     " + i);                         public static void main(String[] args) {          hello h1=new hello("線程A");          Thread demo= new Thread(h1);          hello h2=new hello("線程B");          Thread demo1=new Thread(h2);          demo.start();          demo1.start();           private String name;  }

【可能的運行結果】:

複製代碼
線程A運行     0
線程B運行    0
線程B運行    1
線程B運行    2
線程B運行    3
線程B運行    4
線程A運行     1
線程A運行     2
線程A運行     3
線程A運行     4
複製代碼

關於選擇繼承Thread還是實現Runnable介面?
其實Thread也是實現Runnable介面的:

?
1 2 3 4 5 6 7 8 class Thread implements Runnable {      //…  public void run() {          if (target != null) {               target.run();                

其實Thread中的run方法調用的是Runnable介面的run方法。不知道大家發現沒有,Thread和Runnable都實現了run方法,這種操作模式其實就是代理模式。

Thread和Runnable的區別:

如果一個類繼承Thread,則不適合資源共用。但是如果實現了Runable介面的話,則很容易的實現資源共用。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 /**  * @author Rollen-Holt 繼承Thread類,不能資源共用  * */  class hello extends Thread {      public void run() {          for (int i = 0; i < 7; i++) {              if (count > 0) {                  System.out.println("count= " + count--);                                      public static void main(String[] args) {          hello h1 = new hello();          hello h2 = new hello();          hello h3 = new hello();          h1.start();          h2.start();          h3.start();           private int count = 5

【運行結果】:

複製代碼
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
count= 5
count= 4
count= 3
count= 2
count= 1
複製代碼

大家可以想象,如果這個是一個買票系統的話,如果count表示的是車票的數量的話,說明並沒有實現資源的共用。

我們換為Runnable介面

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 class MyThread implements Runnable{           private int ticket = 5//5張票           public void run() {          for (int i=0; i<=20; i++) {              if (this.ticket > 0) {                  System.out.println(Thread.currentThread().getName()+ "正在賣票"+this.ticket--);                             public class lzwCode {               public static void main(String [] args) {          MyThread my = new MyThread();          new Thread(my, "1號視窗").start();          new Thread(my, "2號視窗").start();          new Thread(my, "3號視窗").start();      

【運行結果】:

count= 5
count= 4
count= 3
count= 2
count= 1

總結一下吧:

實現Runnable介面比繼承Thread類所具有的優勢:

1):適合多個相同的程式代碼的線程去處理同一個資源

2):可以避免java中的單繼承的限制

3):增加程式的健壯性,代碼可以被多個線程共用,代碼和數據獨立。
所以,本人建議大家儘量實現介面。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 /**  * @author Hashsound  * 取得線程的名稱  * */  class hello implements Runnable {      public void run() {          for (int i = 0; i < 3; i++) {              System.out.println(Thread.currentThread().getName());                         public static void main(String[] args) {          hello he = new hello();          new Thread(he,"A").start();          new Thread(he,"B").start();          new Thread(he).start();      

【運行結果】:

複製代碼
A
A
A
B
B
B
Thread-0
Thread-0
Thread-0
複製代碼

說明如果我們沒有指定名字的話,系統自動提供名字。
提醒一下大家:main方法其實也是一個線程。在java中所以的線程都是同時啟動的,至於什麼時候,哪個先執行,完全看誰先得到CPU的資源。
在java中,每次程式運行至少啟動2個線程。一個是main線程,一個是垃圾收集線程。因為每當使用java命令執行一個類的時候,實際上都會啟動一個JVM,每一個jVM實習在就是在操作系統中啟動了一個進程。

判斷線程是否啟動

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 /**  * @author Hashsound 判斷線程是否啟動  * */  class hello implements Runnable {      public void run() {          for (int i = 0; i < 3; i++) {              System.out.println(Thread.currentThread().getName());                         public static void main(String[] args) {          hello he = new hello();          Thread demo = new Thread(he);          System.out.println("線程啟動之前---》" + demo.isAlive());          demo.start();          System.out.println("線程啟動之後---》" + demo.isAlive());      

【運行結果】

線程啟動之前---》false
線程啟動之後---》true
Thread-0
Thread-0
Thread-0

主線程也有可能在子線程結束之前結束。並且子線程不受影響,不會因為主線程的結束而結束。

線程的強制執行:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 /**  * @author Hashsound 線程的強制執行  * */  class hello implements Runnable {      public void run() {          for (int i = 0; i < 3; i++) {              System.out.println(Thread.currentThread().getName());                         public static void main(String[] args) {          hello he = new hello();          Thread demo = new Thread(he,"線程");          demo.start();          for(int i=0;i<50;++i){              if(i>10){                  try                     demo.join();  //強制執行demo                  }catch (Exception e) {                      e.printStackTrace();                                            System.out.println("main 線程執行-->"+i);               

【運行的結果】:

複製代碼
main 線程執行-->0
main 線程執行-->1
main 線程執行-->2
main 線程執行-->3
main 線程執行-->4
main 線程執行-->5
main 線程執行-->6
main 線程執行-->7
main 線程執行-->8
main 線程執行-->9
main 線程執行-->10
線程
線程
線程
main 線程執行-->11
main 線程執行-->12
main 線程執行-->13
...
複製代碼

線程的休眠:

複製代碼
/** 
 * @author Hashsound 線程的休眠 
 * */  
class hello implements Runnable {  
    public void run() {  
        for (int i = 0; i < 3; i++) {  
            try {  
                Thread.sleep(2000);  
            } catch (Exception e) {  
                e.printStackTrace();  
            }  
            System.out.println(Thread.currentThread().getName() + i);  
        }  
    }  
   
    public static void main(String[] args) {  
        hello he = new hello();  
        Thread demo = new Thread(he, "線程");  
        demo.start();  
    }  
}  
<
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 同步和非同步。js是單線程的,由於執行ajax請求會消耗一定的時間,甚至出現了網路故障而遲遲得不到返回結果;這時,如果同步執行的話,就必須等到ajax返回結果以後才能執行接下來的代碼,如果ajax請求需要1分鐘,程式就得等1分鐘。如果是非同步執行的話,就是告訴ajax代碼“老兄,既然你遲遲不返回結果,我 ...
  • 最近在學習Vue2,遇到有些頁面請求數據需要用戶登錄許可權、伺服器響應不符預期的問題,但是總不能每個頁面都做單獨處理吧,於是想到axios提供了攔截器這個好東西,再於是就出現了本文。用戶鑒權與重定向:使用Vue提供的路由導航鉤子;請求數據序列化:使用axios提供的請求攔截器;介面報錯信息處理:使用a... ...
  • 一、場景描述 (一)問題 系統中最初使用Crystal Report(水晶報表)工具生成報表,並將報表發送給客戶端查看,此時定義一CrystalReport工具類即可完成水晶報表的生成工作。 後續報表工具增加SSRS報表(SQL Server Report Service),此時可定義SSRSRep ...
  • 最近在讀《Head First設計模式》一書,此系列會引用源書內容,但文章內容會更加直接,以及加入一些自己的理解。 觀察者模式(有時又被稱為模型-視圖(View)模式、源-收聽者(Listener)模式或從屬者模式)。在此種模式中,一個目標物件管理所有相依於它的觀察者物件,並且在它本身的狀態改變時主 ...
  • 責任鏈的目的是通過特定的設計對請求者和接收者之間進行解耦,請求者調用操作的對象,接收者接收請求並執行相關操作,通過解耦請求者不需要關心接收者的介面,同時也可增強職責的靈活性,通過改變鏈內的成員或調用次序,允許動態新增或刪除責任。 作用 責任鏈模式通過將多個對象連成鏈式模式,並沿著這個鏈傳遞命令或者請 ...
  • 工作流模塊 1.模型管理 :web線上流程設計器、預覽流程xml、導出xml、部署流程 2.流程管理 :導入導出流程資源文件、查看流程圖、根據流程實例反射出流程模型、激活掛起 3.運行中流程:查看流程信息、當前任務節點、當前流程圖、作廢暫停流程、指派待辦人 4.歷史的流程:查看流程信息、流程用時、流 ...
  • 1、一個".java"源文件中是否可以包括多個類(不是內部類)?有什麼限制? 可以有多個類,但只能有一個public的類,並且public的類名必須與文件名相一致。 2、Java有沒有goto? java中的保留字,現在沒有在java中使用。 3、說說&和&&的區別。 &和&&都可以用作邏輯與的運算 ...
  • Nexus2可以通過管理界面來上傳jar包到私庫中,而最新的Nexus3卻找不到了上傳界面,只能通過以下方式來發佈到私庫。 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...