Java 執行緒 run() 方法



描述

如果此執行緒是使用單獨的 Runnable run 物件構造的,則呼叫Java Thread run() 方法,否則此方法不執行任何操作並返回。

宣告

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

public void run()

引數

返回值

此方法不返回值。

異常

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

以下示例顯示了 Java Thread run() 方法的使用。在此程式中,我們透過實現 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 run() 方法的使用。在此程式中,我們透過擴充套件 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
廣告