- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get current thread in Java
A thread can be created by implementing the Runnable interface and overriding the run() method.
The current thread is the currently executing thread object in Java. The method currentThread() of the Thread class can be used to obtain the current thread. This method requires no parameters.
A program that demonstrates this is given as follows −
Example
public class Demo extends Thread { public void run() { for (int i = 0; i < 5; i++) { System.out.println("The Thread name is " + Thread.currentThread().getName()); } } public static void main(String[] args) { Demo t1 = new Demo(); t1.setName("Main Thread"); t1.start(); Thread t2 = currentThread(); t2.setName("Current Thread"); for (int i = 0; i < 5; i++) { System.out.println("The Thread name is " + t1.currentThread().getName()); } } }
Output
The output of the above program is as follows −
The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Current Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread The Thread name is Main Thread
Advertisements