1. 程式人生 > 其它 >JAVA面向物件學習——java多執行緒———菜鳥教程記錄

JAVA面向物件學習——java多執行緒———菜鳥教程記錄

Java 多執行緒程式設計

Java 給多執行緒程式設計提供了內建的支援。 一條執行緒指的是程序中一個單一順序的控制流,一個程序中可以併發多個執行緒,每條執行緒並行執行不同的任務。

多執行緒是多工的一種特別的形式,但多執行緒使用了更小的資源開銷。

 

這裡定義和執行緒相關的另一個術語 - 程序:一個程序包括由作業系統分配的記憶體空間,包含一個或多個執行緒。

 

一個執行緒不能獨立的存在,它必須是程序的一部分。

一個程序一直執行,直到所有的非守護執行緒都結束執行後才能結束。

多執行緒能滿足程式設計師編寫高效率的程式來達到充分利用 CPU 的目的。


一個執行緒的生命週期

執行緒是一個動態執行的過程,它也有一個從產生到死亡的過程。

下圖顯示了一個執行緒完整的生命週期。

 

 

  • 新建狀態:

    使用 new 關鍵字和 Thread 類或其子類建立一個執行緒物件後,該執行緒物件就處於新建狀態。它保持這個狀態直到程式 start() 這個執行緒。

  • 就緒狀態:

    當執行緒物件呼叫了start()方法之後,該執行緒就進入就緒狀態。就緒狀態的執行緒處於就緒佇列中,要等待JVM裡執行緒排程器的排程。

  • 執行狀態:

    如果就緒狀態的執行緒獲取 CPU 資源,就可以執行 run(),此時執行緒便處於執行狀態。處於執行狀態的執行緒最為複雜,它可以變為阻塞狀態、就緒狀態和死亡狀態。

  • 阻塞狀態:

    如果一個執行緒執行了sleep(睡眠)、suspend(掛起)等方法,失去所佔用資源之後,該執行緒就從執行狀態進入阻塞狀態。在睡眠時間已到或獲得裝置資源後可以重新進入就緒狀態。可以分為三種:

    • 等待阻塞:執行狀態中的執行緒執行 wait() 方法,使執行緒進入到等待阻塞狀態。

    • 同步阻塞:執行緒在獲取 synchronized 同步鎖失敗(因為同步鎖被其他執行緒佔用)。

    • 其他阻塞:通過呼叫執行緒的 sleep() 或 join() 發出了 I/O 請求時,執行緒就會進入到阻塞狀態。當sleep() 狀態超時,join() 等待執行緒終止或超時,或者 I/O 處理完畢,執行緒重新轉入就緒狀態。

  • 死亡狀態:

    一個執行狀態的執行緒完成任務或者其他終止條件發生時,該執行緒就切換到終止狀態。


執行緒的優先順序

每一個 Java 執行緒都有一個優先順序,這樣有助於作業系統確定執行緒的排程順序。

Java 執行緒的優先順序是一個整數,其取值範圍是 1 (Thread.MIN_PRIORITY ) - 10 (Thread.MAX_PRIORITY )。

預設情況下,每一個執行緒都會分配一個優先順序 NORM_PRIORITY(5)。

具有較高優先順序的執行緒對程式更重要,並且應該在低優先順序的執行緒之前分配處理器資源。但是,執行緒優先順序不能保證執行緒執行的順序,而且非常依賴於平臺。


建立一個執行緒

Java 提供了三種建立執行緒的方法:

  • 通過實現 Runnable 介面;
  • 通過繼承 Thread 類本身;
  • 通過 Callable 和 Future 建立執行緒。

通過實現 Runnable 介面來建立執行緒

建立一個執行緒,最簡單的方法是建立一個實現 Runnable 介面的類。

為了實現 Runnable,一個類只需要執行一個方法呼叫 run(),宣告如下:

 

public void run()

 

你可以重寫該方法,重要的是理解的 run() 可以呼叫其他方法,使用其他類,並宣告變數,就像主執行緒一樣。

 

在建立一個實現 Runnable 介面的類之後,你可以在類中例項化一個執行緒物件。

 

Thread 定義了幾個構造方法,下面的這個是我們經常使用的:

  Thread(Runnable threadOb,String threadName);

這裡,threadOb 是一個實現 Runnable 介面的類的例項,並且 threadName 指定新執行緒的名字。

 

新執行緒建立之後,你呼叫它的 start() 方法它才會執行。

void start();

 

 

=============================================================================

 

示例:

 

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // 讓執行緒睡眠一會
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
 
   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}

  

 

編譯以上程式執行結果如下:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

 

 

-----------------------------------------------------------------------------------------

 

class RunnableDemo implements Runnable
{
    private Thread t;
    private String threadName;

    RunnableDemo( String name)
    {
        threadName = name;
        System.out.println("Creating " +  threadName );
    }

    public void start ()
    {
        System.out.println("Starting " +  threadName );
        if (t == null)
        {
            t = new Thread (this, threadName);
            t.start ();
        }
    }

    public void run()
    {
        System.out.println("Running " +  threadName );
        try {
            for(int i = 4; i > 0; i--)
            {
                System.out.println("Thread: " + threadName + ", " + i);

                Thread.sleep(50);
            }
        }catch (InterruptedException e)
        {
            System.out.println("Thread " +  threadName + " interrupted.");
        }
        System.out.println("Thread " +  threadName + " exiting.");
    }

}

public class TestThread
{
    public static void main(String args[])
    {
        RunnableDemo R1 = new RunnableDemo( "Thread-1");
        R1.start();

        RunnableDemo R2 = new RunnableDemo( "Thread-2");
        R2.start();
    }
}

  

 

下午 10:56:13: Executing task 'TestThread.main()'...

Starting Gradle Daemon...
Gradle Daemon started in 8 s 662 ms
> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :TestThread.main()

 

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-2, 2
Thread: Thread-1, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-2 exiting.
Thread Thread-1 exiting.

 

 

BUILD SUCCESSFUL in 26s
2 actionable tasks: 2 executed
下午 10:56:54: Task execution finished 'TestThread.main()'.

 

 

 

 

=================================================================

 

=================================================================

 

 

 

通過繼承Thread來建立執行緒

 

建立一個執行緒的第二種方法是建立一個新的類,該類繼承 Thread 類,然後建立一個該類的例項。

繼承類必須重寫 run() 方法,該方法是新執行緒的入口點。它也必須呼叫 start() 方法才能執行。

該方法儘管被列為一種多執行緒實現方式,但是本質上也是實現了 Runnable 介面的一個例項。

 

示例:

class ThreadDemo extends Thread {
   private Thread t;
   private String threadName;
   
   ThreadDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // 讓執行緒睡眠一會
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}
 
public class TestThread {
 
   public static void main(String args[]) {
      ThreadDemo T1 = new ThreadDemo( "Thread-1");
      T1.start();
      
      ThreadDemo T2 = new ThreadDemo( "Thread-2");
      T2.start();
   }   
}

  

 

編譯以上程式執行結果如下:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.

 

 

------------------------------------------------------------------------------------

 

class ThreadDemo extends Thread {
    private Thread t;
    private String threadName;

    ThreadDemo( String name)
    {
        threadName = name;
        System.out.println("Creating " +  threadName );
    }

    public void start ()
    {
        System.out.println("Starting " +  threadName );
        if (t == null)
        {
            t = new Thread (this, threadName);
            t.start ();
        }
    }

    public void run()
    {
        System.out.println("Running " +  threadName );
        try {
            for(int i = 4; i > 0; i--)
            {
                System.out.println("Thread: " + threadName + ", " + i);
                Thread.sleep(50);
            }
        }catch (InterruptedException e)
        {
            System.out.println("Thread " +  threadName + " interrupted.");
        }
        System.out.println("Thread " +  threadName + " exiting.");
    }

}

public class TestThread
{

    public static void main(String args[])
    {
        ThreadDemo T1 = new ThreadDemo( "Thread-1");
        T1.start();

        ThreadDemo T2 = new ThreadDemo( "Thread-2");
        T2.start();
    }
}

  

下午 11:00:23: Executing task 'TestThread.main()'...

> Task :compileJava
> Task :processResources NO-SOURCE
> Task :classes

> Task :TestThread.main()

 

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-2, 3
Thread: Thread-1, 3
Thread: Thread-2, 2
Thread: Thread-1, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-2 exiting.
Thread Thread-1 exiting.

 

 

BUILD SUCCESSFUL in 2s
2 actionable tasks: 2 executed
下午 11:00:26: Task execution finished 'TestThread.main()'.

 

 

 

 

--------------------------------------------------------------------------------------------------------

 

 

Thread 方法

下表列出了Thread類的一些重要方法:

序號 方法描述
1 public void start()
使該執行緒開始執行;Java 虛擬機器呼叫該執行緒的 run 方法。
2 public void run()
如果該執行緒是使用獨立的 Runnable 執行物件構造的,則呼叫該 Runnable 物件的 run 方法;否則,該方法不執行任何操作並返回。
3 public final void setName(String name)
改變執行緒名稱,使之與引數 name 相同。
4 public final void setPriority(int priority)
 更改執行緒的優先順序。
5 public final void setDaemon(boolean on)
將該執行緒標記為守護執行緒或使用者執行緒。
6 public final void join(long millisec)
等待該執行緒終止的時間最長為 millis 毫秒。
7 public void interrupt()
中斷執行緒。
8 public final boolean isAlive()
測試執行緒是否處於活動狀態。

上述方法是被 Thread 物件呼叫的,下面表格的方法是 Thread 類的靜態方法。

序號 方法描述
1 public static void yield()
暫停當前正在執行的執行緒物件,並執行其他執行緒。
2 public static void sleep(long millisec)
在指定的毫秒數內讓當前正在執行的執行緒休眠(暫停執行),此操作受到系統計時器和排程程式精度和準確性的影響。
3 public static boolean holdsLock(Object x)
當且僅當當前執行緒在指定的物件上保持監視器鎖時,才返回 true。
4 public static Thread currentThread()
返回對當前正在執行的執行緒物件的引用。
5 public static void dumpStack()
將當前執行緒的堆疊跟蹤列印至標準錯誤流。