线程类静态线程currentThread() (Thread Class static Thread currentThread())
This method is available in package java.lang.Thread.currentThread().
软件包java.lang.Thread.currentThread()中提供了此方法。
This method is used to return a reference of the currently executing thread object.
此方法用于返回当前正在执行的线程对象的引用。
This method is static so this method is accessible with classname too.
此方法是静态的,因此也可以使用类名访问此方法。
The return type of this method is Thread, it returns a reference of currently executing thread object.
该方法的返回类型为Thread ,它返回当前正在执行的线程对象的引用。
This method does not raise any exception.
此方法不会引发任何异常。
Syntax:
句法:
static Thread currentThread(){
}
Parameter(s):
参数:
We don't pass any object as a parameter in the method of the File.
我们不会在File方法中将任何对象作为参数传递。
Return value:
返回值:
The return type of this method is Thread, it returns reference of current executing thread.
该方法的返回类型为Thread ,它返回当前正在执行的线程的引用。
Java程序演示currentThread()方法的示例 (Java program to demonstrate example of currentThread() method)
/* We will use Thread class methods so we are importing
the package but it is not mandate because
it is imported by default
*/
import java.lang.Thread;
class Thread1 extends Thread {
// Override run() of Thread class
public void run() {
/* Display a thread name of current executing thread
by using Thread.currentThread().getName()
*/
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
}
}
class Thread2 extends Thread {
public void run() {
/* Display a thread name of current executing thread by
using Thread.currentThread().getName()
*/
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
}
}
public class MainThread {
public static void main(String[] args) {
/* Display a thread name of current executing thread by
using Thread.currentThread().getName()
*/
System.out.println("The name of this thread is " + " " + Thread.currentThread().getName());
// Creating Thread1 object
Thread1 t1 = new Thread1();
// By using start() Thread class start() will call and
// it will call run() of Thread1 class
t1.start();
Thread2 t2 = new Thread2();
// By using start() Thread class start() will call
// and it will call run() of Thread2 class
t2.start();
}
}
Output
输出量
E:\Programs>javac MainThread.java
E:\Programs>java MainThread
The name of this thread is main
The name of this thread is Thread-0
The name of this thread is Thread-1
翻译自: https://www.includehelp.com/java/thread-class-static-thread-currentthread-method-with-example.aspx