Thread currentThread() method in Java

Method delaration- public static native Thread currentThread().

Thread’s currentThread() is a static and native method which returns current executing thread. This method is native that means implementation has been written in some different language like c/c++. if you look into the source code, you will find no implementation logic in Thread.java file. This method can be used to get current executing thread name.

 

package multithreading;

public class ThreadCurrentThreadExample {
	public static void main(String[] args) {
		System.out.println(Thread.currentThread());
	}
}

Output is – Thread[main,5,main]

Let’s see another example where we will have two user-defined thread.

package multithreading;

public class ThreadCurrentThreadExample {
	public static void main(String[] args) {
		Thread thread1 = new Thread() {
			public void run() {
				System.out.println("Using Thread :- " + Thread.currentThread().getName());
			}
		};

		thread1.start();

		Runnable r = new Runnable() {
			public void run() {
				System.out.println("Using runnable :- " + Thread.currentThread().getName());
			}
		};

		Thread thread2 = new Thread(r);
		thread2.start();
		System.out.println(Thread.currentThread().getName());
	}
}

Output is –

Using Thread :- Thread-0
main
Using runnable :- Thread-1

Note – The output sequence can change. It depends on thread scheduler which thread it picks first.