2025-05-17

學習一下java多線程

 

實現java多線程主要有實現Runnable接口,實現run方法和繼承Thread類。重寫run方法。

 

首先說一些這兩種實現方式的區別:

 


①Thread類在API中的定義是這樣的,public class Thread extends Object implements Runnable

可以看到,Thread類是實現瞭Runnable接口的,Runnable接口中隻有一個方法,就是public void run(){}這個方法,而在Thread裡面有很多的方法,除瞭重寫瞭run方法之外還有四個構造方法,public void start(){}等方法。

這就說明這個線程類比這個接口更多的關於線程的操作。

 


②當我們需要實現一個線程的時候,但恰恰這個時候它已經有瞭一個父類,由於java是單繼承的,所以我們不能再繼承一個Thread類瞭,這個時候就隻好實現Runable接口瞭。

 


③當我們定義瞭一個實現瞭Runable接口的類的對象的時候,我們可以開啟多個線程,而實現瞭Thread類的對象就不行瞭(它隻能調用start方法一次)。

 

線程的執行是隨機性的,線程有五種狀態:新建,就緒,運行,阻塞,死亡。隻有當線程獲得瞭所需要的所有資源並且獲得瞭CPU分配的時間片才能運行,當程序一切就緒之後也不一定會運行。就像下面的程序。

 

Java代碼 
package threadTest1;  
public class TestThread {  
    public static void main(String[] args) {  
        test a=new test("A");  
        test b=new test("B");  
        test c=new test("C");  
        a.start();  
        b.start();  
        c.start();  
        }  
    }  
    class test extends Thread{  
        private String name;  
        public test(String str){  
            this.name=str;  
        }  
        public void run(){  
            System.out.println("我是線程:"+name);  
        }  

package threadTest1;
public class TestThread {
 public static void main(String[] args) {
  test a=new test("A");
  test b=new test("B");
  test c=new test("C");
  a.start();
  b.start();
  c.start();
  }
 }
 class test extends Thread{
  private String name;
  public test(String str){
   this.name=str;
  }
  public void run(){
   System.out.println("我是線程:"+name);
  }
}
它的執行結果是隨機的,可能是ABC,也可能是ACB,還可能是BCA==。

我們上課的老師說這樣的程序能夠順序執行,其實是不對的。

 

線程的執行 :線程的執行是使用start方法,而不是run方法,run方法隻是一個普通方法,真正要實現線程的同步是要使用start方法的。

線程睡眠 :線程可以通過調用sleep方法,這個方法是在Thread類中定義的,線程由運行狀態進入睡眠狀態,當時間完成之後再次進入等待狀態,有人說時間到瞭就到瞭運行狀態其實是不對的,隻能說它到瞭等待狀態等待CPU的調度。

 

中斷線程 :終端線程是一個很讓我困惑的事情,因為調用瞭interrupt方法之後線程也沒有中斷,比如我的程序

Java代碼 
package test5;  
 
public class TestThread1 {  
 
    public static void main(String[] args) {  
        Thread thread1 = new test();  
        thread1.start();  
    }  
}  
 
class test extends Thread{  
    public void run(){  
        while(true){  
            System.out.println("程序開始運行");  
            this.interrupt();  
            System.out.println("程序結束運行");  
        }  
    }  

package test5;

public class TestThread1 {

 public static void main(String[] args) {
  Thread thread1 = new test();
  thread1.start();
 }
}

class test extends Thread{
 public void run(){
  while(true){
   System.out.println("程序開始運行");
   this.interrupt();
   System.out.println("程序結束運行");
  }
 }
}程序就真的可以無限運行下去,那他到底有什麼用呢?

 

有人的解釋是:

在java中,線程的中斷(interrupt)隻是改變瞭線程的中斷狀態,至於這個中斷狀態改變後帶來的結果,那是無法確定的,有時它更是讓停止中的線程繼續執行的唯一手段.不但不是讓線程停止運行,反而是繼續執行線程的手段.

總之大傢必須知道它的作用絕不是那麼的簡單。具體的深入的我將在下一篇博客裡講述。

 

線程中斷 :在大多數資料裡,因時間片用完而被剝奪CPU的情況我們叫做線程中斷。

 

線程等待 :它有兩個重載的方法可以將線程切換到等待狀態

this.wait();
this.wait(timeout);
this.wait(timeout, nanos);

他們的作用不贅述瞭,沒有參數的這種等待隻有在notify方法或者notifyAll才能結束等待。

線程等待與睡眠的區別是:睡眠不會導致資源的釋放,而等待可以。其他線程可能得到這些資源。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *