The Java Thread currentThread() method returns a reference to the currently executing thread object.
DeclarationFollowing is the declaration for java.lang.Thread.currentThread() method
public static Thread currentThread()Parameters
NA
Return ValueThis method returns the currently executing thread.
ExceptionNA
Example: Getting Current Thread in Multi-threaded programThe following example shows the usage of Java Thread currentThread() method. In this example, we've created a thread class ThreadDemo by implementing Runnable Interface. In ThreadDemo constructor currently active thread is retrieved using currentThread method, a new thread is created and both are printed.
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(); } }Output
Let us compile and run the above program, this will produce the following result −
current thread = Thread[main,5,main] thread created = Thread[Admin Thread,5,main] This is run() methodExample: Getting Current Thread in Single-threaded program
The following example shows the usage of Java Thread currentThread() method. In this example, we've created a thread class ThreadDemo. In main method, currently active thread is retrieved using currentThread method, and is printed.
package com.tutorialspoint; public class ThreadDemo { public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("current thread = " + currThread); } }Output
Let us compile and run the above program, this will produce the following result −
current thread = Thread[#1,main,5,main]
java_lang_thread.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4