Java Thread start() 方法



描述

Java Thread start() 方法啟動該執行緒的執行,Java虛擬機器將呼叫該執行緒的run方法。結果是兩個執行緒併發執行:當前執行緒(從對start方法的呼叫返回)和另一個執行緒(執行其run方法)。

宣告

以下是java.lang.Thread.start() 方法的宣告

public void start()

引數

返回值

此方法不返回值。

異常

IllegalThreadStateException − 如果執行緒已經啟動。

示例:啟動實現Runnable介面的執行緒

以下示例顯示了Java Thread start() 方法的用法。在這個程式中,我們透過實現Runnable介面建立了一個執行緒類ThreadDemo。在建構函式中,使用new Thread建立了一個新執行緒。使用start()啟動執行緒,當執行緒被排程執行時,它將依次呼叫run()方法。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   Thread t;
   ThreadDemo() {
    
      // thread created
      t = new Thread(this, "Admin Thread");
     
      // prints thread created
      System.out.println("thread  = " + t);
      
      // this will call run() function
      System.out.println("Calling run() function... ");
      t.start();
   }

   public void run() {
      System.out.println("Inside run() function");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

thread = Thread[Admin Thread,5,main]
Calling run() function...
Inside run() function

示例:啟動繼承Thread類的執行緒

以下示例顯示了Java Thread start() 方法的用法。在這個程式中,我們透過繼承Thread類建立了一個執行緒類ThreadDemo。在建構函式中,使用new Thread建立了一個新執行緒。使用start()啟動執行緒,當執行緒被排程執行時,它將依次呼叫run()方法。

package com.tutorialspoint;

public class ThreadDemo extends Thread {

   Thread t;
   ThreadDemo() {
    
      // thread created
      t = new Thread(this, "Admin Thread");
     
      // prints thread created
      System.out.println("thread  = " + t);
      
      // this will call run() function
      System.out.println("Calling run() function... ");
      t.start();
   }

   public void run() {
      System.out.println("Inside run() function");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
} 

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

thread = Thread[Admin Thread,5,main]
Calling run() function...
Inside run() function
java_lang_thread.htm
廣告