Java Current Thread


 

Java Current Thread

In this tutorial, we are using Thread.currentThread() method to find the current thread name.

In this tutorial, we are using Thread.currentThread() method to find the current thread name.

Java Current Thread

In this tutorial, we are using Thread.currentThread() method to find the current thread name.

Thread.currentThread() :

Thread class provides method to display the current running thread. It is static Thread method so that there is no need to call a reference to a Thread object. It returns the current running thread object reference.

public static Thread currentThread() : This method returns a reference to the currently running thread object.

Example : In this example we are displaying the current running thread by calling currentThread() method.

class NewCurrentThread implements Runnable {

	NewCurrentThread(String name) {
		Thread thread = new Thread(this, name);
		thread.start();
	}

	public void run() {
		/* Returns currently executing thread object. */
		Thread thread = Thread.currentThread();
		System.out.println("Welcome in Thread " + thread.getName());
	}
}

public class CurrentThread {
	public static void main(String args[]) {
		new NewCurrentThread("One");
		new NewCurrentThread("Two");
	}
}

Output :

Welcome in Thread One
Welcome in Thread Two

Ads