Java並發編程:Thread類的使用,java並發thread類

來源:互聯網
上載者:User

Java並發編程:Thread類的使用,java並發thread類
Java並發編程:Thread類的使用    以下是本文的目錄大綱:  一.線程的狀態  二.環境切換  三.Thread類中的方法    轉載自:   http://www.cnblogs.com/dolphin0520/p/3920357.html一.線程的狀態  線程從建立到最終的消亡,要經曆若干個狀態。一般來說,線程包括以下這幾個狀態:建立(new)、就緒(runnable)、運行(running)、阻塞(blocked)、time waiting、waiting、消亡(dead)。    下面這副圖描述了線程從建立到消亡之間的狀態:

 

  在有些教程上將blocked、waiting、time waiting統稱為阻塞狀態,這個也是可以的,只不過這裡我想將線程的狀態和Java中的方法調用聯絡起來,所以將waiting和time waiting兩個狀態分離出來。二.環境切換  對於單核CPU來說(對於多核CPU,此處就理解為一個核),CPU在一個時刻只能運行一個線程,當在運行一個線程的過程中轉去運行另外一個線程,這個叫做線程環境切換(對於進程也是類似)。  三.Thread類中的方法  通過查看java.lang.Thread類的源碼可知:  

 

  Thread類實現了Runnable介面,在Thread類中,有一些比較關鍵的屬 性,比如name是表示Thread的名字,可以通過Thread類的構造器中的參數來指定線程名字,priority表示線程的優先順序(最大值為10, 最小值為1,預設值為5),daemon表示線程是否是守護線程,target表示要執行的任務。  下面是Thread類中常用的方法:  以下是關係到線程運行狀態的幾個方法:  1)start方法  start()用來啟動一個線程,當調用start方法後,系統才會開啟一個新的線程來執行使用者定義的子任務,在這個過程中,會為相應的線程分配需要的資源。  2)run方法  run()方法是不需要使用者來調用的,當通過start方法啟動一個線程之後,當線程獲得了CPU執行時間,便進入run方法體去執行具體的任務。注意,繼承Thread類必須重寫run方法,在run方法中定義具體要執行的任務。  3)sleep方法  sleep方法有兩個重載版本:
123 sleep(long millis)     //參數為毫秒 sleep(long millis,int nanoseconds)    //第一參數為毫秒,第二個參數為納秒
  sleep相當於讓線程睡眠,交出CPU,讓CPU去執行其他的任務。  但是有一點要非常注意,sleep方法不會釋放鎖,也就是說如果當前線程持有對某個對象的鎖,則即使調用sleep方法,其他線程也無法訪問這個對象。看下面這個例子就清楚了:
123456789101112131415161718192021222324252627282930313233 public class Test {         private int i = 10;    private Object object = new Object();         public static void main(String[] args) throws IOException  {        Test test = new Test();        MyThread thread1 = test.new MyThread();        MyThread thread2 = test.new MyThread();        thread1.start();        thread2.start();    }               class MyThread extends Thread{        @Override        public void run() {            synchronized (object) {                i++;                System.out.println("i:"+i);                try {                    System.out.println("線程"+Thread.currentThread().getName()+"進入睡眠狀態");                    Thread.currentThread().sleep(10000);                } catch (InterruptedException e) {                    // TODO: handle exception                }                System.out.println("線程"+Thread.currentThread().getName()+"睡眠結束");                i++;                System.out.println("i:"+i);            }        }    }}
   輸出結果:  

 

  從上面輸出結果可以看出,當Thread-0進入睡眠狀態之後,Thread-1並沒有去執行具體的任務。只有當Thread-0執行完之後,此時Thread-0釋放了對象鎖,Thread-1才開始執行。  注意,如果調用了sleep方法,必須捕獲InterruptedException異常或者將該異常向上層拋出。當線程睡眠時間滿後,不一定會立即得到執行,因為此時可能CPU正在執行其他的任務。所以說調用sleep方法相當於讓線程進入阻塞狀態。  4)yield方法  調用yield方法會讓當前線程交出CPU許可權,讓CPU去執行其他的線程。它跟sleep方法類似,同樣不會釋放鎖。但是yield不能控制具體的交出CPU的時間,另外,yield方法只能讓擁有相同優先順序的線程有擷取CPU執行時間的機會。  注意,調用yield方法並不會讓線程進入阻塞狀態,而是讓線程重回就緒狀態,它只需要等待重新擷取CPU執行時間,這一點是和sleep方法不一樣的。  5)join方法  join方法有三個重載版本:
123 join()join(long millis)     //參數為毫秒join(long millis,int nanoseconds)    //第一參數為毫秒,第二個參數為納秒
   假如在main線程中,調用thread.join方法,則main方法會等待thread線程執行完畢或者等待一定的時間。如果調用的是無參join方法,則等待thread執行完畢,如果調用的是指定了時間參數的join方法,則等待一定的事件。  看下面一個例子:
123456789101112131415161718192021222324252627282930 public class Test {         public static void main(String[] args) throws IOException  {        System.out.println("進入線程"+Thread.currentThread().getName());        Test test = new Test();        MyThread thread1 = test.new MyThread();        thread1.start();        try {            System.out.println("線程"+Thread.currentThread().getName()+"等待");            thread1.join();            System.out.println("線程"+Thread.currentThread().getName()+"繼續執行");        } catch (InterruptedException e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }          class MyThread extends Thread{        @Override        public void run() {            System.out.println("進入線程"+Thread.currentThread().getName());            try {                Thread.currentThread().sleep(5000);            } catch (InterruptedException e) {                // TODO: handle exception            }            System.out.println("線程"+Thread.currentThread().getName()+"執行完畢");        }    }}
   輸出結果:  

 

  可以看出,當調用thread1.join()方法後,main線程會進入等待,然後等待thread1執行完之後再繼續執行。  實際上調用join方法是調用了Object的wait方法,這個可以通過查看源碼得知:  

 

  wait方法會讓線程進入阻塞狀態,並且會釋放線程佔有的鎖,並交出CPU執行許可權。  由於wait方法會讓線程釋放對象鎖,所以join方法同樣會讓線程釋放對一個對象持有的鎖。具體的wait方法使用在後面文章中給出。  6)interrupt方法  interrupt,顧名思義,即中斷的意思。單獨調用interrupt方法可以使得處於阻塞狀態的線程拋出一個異常,也就說,它可以用來中斷一個正處於阻塞狀態的線程;另外,通過interrupt方法和isInterrupted()方法來停止正在啟動並執行線程。  下面看一個例子:
12345678910111213141516171819202122232425262728 public class Test {         public static void main(String[] args) throws IOException  {        Test test = new Test();        MyThread thread = test.new MyThread();        thread.start();        try {            Thread.currentThread().sleep(2000);        } catch (InterruptedException e) {                     }        thread.interrupt();    }          class MyThread extends Thread{        @Override        public void run() {            try {                System.out.println("進入睡眠狀態");                Thread.currentThread().sleep(10000);                System.out.println("睡眠完畢");            } catch (InterruptedException e) {                System.out.println("得到中斷異常");            }            System.out.println("run方法執行完畢");        }    }}
   輸出結果:  

 

  從這裡可以看出,通過interrupt方法可以中斷處於阻塞狀態的線程。那麼能不能中斷處於非阻塞狀態的線程呢?看下面這個例子:
12345678910111213141516171819202122232425 public class Test {         public static void main(String[] args) throws IOException  {        Test test = new Test();        MyThread thread = test.new MyThread();        thread.start();        try {            Thread.currentThread().sleep(2000);        } catch (InterruptedException e) {                     }        thread.interrupt();    }          class MyThread extends Thread{        @Override        public void run() {            int i = 0;            while(i<Integer.MAX_VALUE){                System.out.println(i+" while迴圈");                i++;            }        }    }}
   運行該程式會發現,while迴圈會一直運行直到變數i的值超出Integer.MAX_VALUE。所以說直接調用interrupt方法不能中斷正在運行中的線程。  但是如果配合isInterrupted()能夠中斷正在啟動並執行線程,因為調用interrupt方法相當於將中斷標誌位置為true,那麼可以通過調用isInterrupted()判斷中斷標誌是否被置位來中斷線程的執行。比如下面這段代碼:
12345678910111213141516171819202122232425 public class Test {         public static void main(String[] args) throws IOException  {        Test test = new Test();        MyThread thread = test.new MyThread();        thread.start();        try {            Thread.currentThread().sleep(2000);        } catch (InterruptedException e) {                     }        thread.interrupt();    }          class MyThread extends Thread{        @Override        public void run() {            int i = 0;            while(!isInterrupted() && i<Integer.MAX_VALUE){                System.out.println(i+" while迴圈");                i++;            }        }    }}
   運行會發現,列印若干個值之後,while迴圈就停止列印了。  但是一般情況下不建議通過這種方式來中斷線程,一般會在MyThread類中增加一個屬性 isStop來標誌是否結束while迴圈,然後再在while迴圈中判斷isStop的值。
1234567891011121314 class MyThread extends Thread{        private volatile boolean isStop = false;        @Override        public void run() {            int i = 0;            while(!isStop){                i++;            }        }                 public void setStop(boolean stop){            this.isStop = stop;        }    }
   那麼就可以在外面通過調用setStop方法來終止while迴圈。  7)stop方法  stop方法已經是一個廢棄的方法,它是一個不安全的方法。因為調用stop方法會直接終止run方法的調用,並且會拋出一個ThreadDeath錯誤,如果線程持有某個對象鎖的話,會完全釋放鎖,導致對象狀態不一致。所以stop方法基本是不會被用到的。  8)destroy方法  destroy方法也是廢棄的方法。基本不會被使用到。  以下是關係到線程屬性的幾個方法:  1)getId  用來得到線程ID  2)getName和setName  用來得到或者設定線程名稱。  3)getPriority和setPriority  用來擷取和設定線程優先順序。  4)setDaemon和isDaemon  用來設定線程是否成為守護線程和判斷線程是否是守護線程。  守護線程和使用者線程的區別在於:守護線程依賴於建立它的線程,而使用者線程則不依賴。舉個 簡單的例子:如果在main線程中建立了一個守護線程,當main方法運行完畢之後,守護線程也會隨著消亡。而使用者線程則不會,使用者線程會一直運行直到其 運行完畢。在JVM中,像垃圾收集器線程就是守護線程。  Thread類有一個比較常用的靜態方法currentThread()用來擷取當前線程。  在上面已經說到了Thread類中的大部分方法,那麼Thread類中的方法調用到底會引起線程狀態發生怎樣的變化呢?下面一幅圖就是在上面的圖上進行改進而來的:

 

  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.