Java Thread currentThread() 方法



描述

Java Thread currentThread() 方法返回对当前正在执行的线程对象的引用。

声明

以下是 java.lang.Thread.currentThread() 方法的声明

public static Thread currentThread()

参数

返回值

此方法返回当前正在执行的线程。

异常

示例:在多线程程序中获取当前线程

以下示例演示了 Java Thread currentThread() 方法的用法。在此示例中,我们通过实现 Runnable 接口创建了一个线程类 ThreadDemo。在 ThreadDemo 构造函数中,使用 currentThread 方法检索当前活动的线程,创建一个新线程并打印两者。

package com.tutorialspoint;

public class ThreadDemo implements Runnable {

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

   public void run() {
      System.out.println("This is run() method");
   }

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

输出

让我们编译并运行上述程序,这将产生以下结果:

current thread = Thread[main,5,main]
thread created = Thread[Admin Thread,5,main]
This is run() method

示例:在单线程程序中获取当前线程

以下示例演示了 Java Thread currentThread() 方法的用法。在此示例中,我们创建了一个线程类 ThreadDemo。在 main 方法中,使用 currentThread 方法检索当前活动的线程,并将其打印出来。

package com.tutorialspoint;

public class ThreadDemo {

   public static void main(String[] args) {

      Thread t = Thread.currentThread();
      System.out.println("current thread = " + currThread);
   }
}   

输出

让我们编译并运行上述程序,这将产生以下结果:

current thread = Thread[#1,main,5,main]
java_lang_thread.htm
广告

© . All rights reserved.