Java Thread toString() 方法



描述

Java Thread toString() 方法返回此執行緒的字串表示形式,包括執行緒的名稱、優先順序和執行緒組。

宣告

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

public String toString()

引數

返回值

此方法返回此執行緒的字串表示形式。

異常

示例:在多執行緒環境中獲取字串表示形式

以下示例演示了 Java Thread toString() 方法的用法。在這個程式中,我們透過實現 Runnable 介面建立了一個執行緒類 ThreadDemo。在建構函式中,使用 new Thread 建立一個新執行緒,並使用 start() 方法啟動它。在 run() 方法中,我們列印執行緒的字串表示形式。在 main 方法中,我們建立三個 ThreadDemo 類的執行緒。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

   Thread t;

   ThreadDemo() {

      t = new Thread(this);
      // this will call run() function
      t.start();
   }

   public void run() {

      // returns a string representation of this thread 
      System.out.println(t.toString());
   }

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

輸出

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

Thread[#22,Thread-1,5,main]
Thread[#23,Thread-2,5,main]
Thread[#21,Thread-0,5,main]

示例:在單執行緒程式中獲取字串表示形式

以下示例演示了 Java Thread toString() 方法的用法。在這個程式中,我們建立了一個類 ThreadDemo。在 main 方法中,使用 currentThread() 方法檢索當前執行緒並列印它。使用 toString(),列印當前執行緒的字串表示形式。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      t.setName("Admin Thread");
      
      // set thread priority to 1
      t.setPriority(1);
     
      // prints the current thread
      System.out.println("Thread = " + t.toString());
      
   }
} 

輸出

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

Thread = Thread[#1,Admin Thread,1,main]
java_lang_thread.htm
廣告
© . All rights reserved.