๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

currentThread() Method with Example  


Introduction
  • currentThread() method is the static method which returns a reference to the Thread object representing the currently executing thread (the code that called this method).
  • Use :-
    • Identify which thread is running (name, id, priority) for logging/debugging.
    • Access or modify the current thread (e.g. Thread.currentThread().setName("...")).
    • Check or clear interrupt status (Thread.currentThread().isInterrupted() / interrupt() on self).
    • Internally used by ThreadLocal and other concurrency utilities to attach per-thread state.
  • Syntax :-
    • public static native Thread currentThread()
  • Program :-
    class MyTask extends Thread
    {
        @Override
        public void run()
        {
            // Identify current thread details
            Thread t = Thread.currentThread();
    
            System.out.println("Id : "+t.getId());
    
            System.out.println("Name 1 : "+t.getName());
    
            // Modify the current thread
            t.setName("Deepak-Thread");
    
            System.out.println("Name 2 : "+t.getName());
        }
    }
    
    public class CurrentThreadDemo
    {
        public static void main(String[] args)
        {
            MyTask t1 = new MyTask();
            t1.start();
        }
    }