Get Current Thread

Ads
 

Get Current Thread

A Thread is the independent path of execution in a program. Many thread runs concurrently with a program.

A Thread is the independent path of execution in a program. Many thread runs concurrently with a program.

Get Current Thread

     

A Thread is the independent path of execution in a program. Many thread runs concurrently with a program. Some threads are Multithread, This thread refers to two or more thread running simultaneously within a program. The thread in java is created and controlled by the java.lang.Threadclass.

Two way to create Thread-

1)Implements Runnable interface.

2)By extending the  Threads class.

Understand with Example

In this Tutorial Example, we want to describe you a code that helps you in understanding Get Current Thread. For this we have a class" Get Current Thread" implements Runnable interface. 

1)A GetCurrentThread implements the Runnable interface, that provides you to execute the thread. An object of GetCurrentThread is Runnable object.

2)We pass the Runnable object as argument to the Thread constructor that is used to create an object of current thread.

3)The Thread object has a Runnable object that implements the run method.

4)Once the thread object is created ,start method is invoked.

5)The start( )return immediately once  a thread has been spawned.

6)Thread.currentThread().get Name());-This method Returns a reference to the currently executing thread object. 

7) The current thread ends when the run( ) method ends, This is done either by normal completion or by throwing an uncaught exception.

On execution the code display you the list of thread executing in a program.

GetCurrentThread.java


public class GetCurrentThread implements Runnable {

  Thread th;
  
  public GetCurrentThread(String threadName) {
  th= new Thread(this,threadName);
  th.start();
  }

  public void run() {
  System.out.println(th.getName()+" is starting.....");
  System.out.println("Current thread name : "+
  Thread.currentThread().getName());
  }

  public static void main(String args[]) {
  System.out.println("Current thread name : "+
  Thread.currentThread().getName());
  new GetCurrentThread("1st Thread");
  new GetCurrentThread("2nd Thread");
  }
}

Output
Current thread name : main
1st Thread is starting.....
Current thread name : 1st Thread
2nd Thread is starting.....
Current thread name : 2nd Thread
 

Download code

Ads

Ads