Main Thread

  • When a java programs starts running the main thread is called as it is the one which execute when program begins.

    The main thread is important for two reasons:

  • It is the thread from which other “child” threads will be generated.

  • it must be the last thread to finish execution because it performs various shutdown actions.

  • java automatically calls main Tread to get reference of that thread we need to create a object for Thread and then call the method as follows

Once we got a reference to a main thread we can control it as another threads.

// Controlling the main Thread.
public class CurrentThreadDemo 
{
 public static void main(String args[]) 
 {
 Thread t = Thread.currentThread();   //creating a thread object and give reference as currentThread.
 System.out.println("Current thread: " + t);  //displays the thread name 
 // change the name of the thread
 t.setName("My Thread");   //sets the name to thread using final void setName(String threadName)
 System.out.println("After name change: " + t);  //displays the changed name
 try 
 {
 for(int n = 5; n > 0; n--) 
 {
 System.out.println(n);
 Threa.sleep(1000);      //static void sleep(long milliseconds) throws InterruptedException will suspend execution for a specified milliseconds
 }                       //static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
 } 
 catch (InterruptedException e)  //to catch the exception thrown by sleep method
 {
 System.out.println("Main thread interrupted");
 }
 }
}

Output:

Current thread: Thread[main,5,main] //Thread[name of the thread, priority, Thread group]
After name change: Thread[My Thread,5,main] //Thread[changed name of the thread, priority, Thread group]
5
4
3
2
1
Thread group-
is a data structure that controls the state of a collection of threads as a whole.

static Thread currentThread( )- This method returns a reference to the thread in which it is called.

final void setName(String threadName)-sets the name for the thread

static void sleep(long milliseconds) throws InterruptedException-This will suspend the execution for a specified milliseconds.

static void sleep(long milliseconds, int nanoseconds) throws InterruptedException-for nano seconds

Creating a Thread

  • We can create a thread by instantiating an object of type Thread.
  • Java defines two ways of creation of thread

You can implement the Runnable interface.

You can extend the Thread class, itself.

  • Implementing Runnable

    To implement Runnable,a class need only implement a single method called run( ), which is declared like this:

// Create a thread by implementing Runnable interface.
class NewThread implements Runnable 
{
 Thread t;
 NewThread() 
 {
 // Create a new second(first is main) thread
 t = new Thread(this, "Demo Thread");  //by constructor Thread(Runnable threadOb, String threadName)
 System.out.println("Child thread: " + t);
 t.start(); // Start the thread
 }

 // This is the entry point for the second thread.
 public void run() 
 {
 try
  {
 for(int i = 3; i > 0; i--) 
 {
 System.out.println("Child Thread: " + i);
 Thread.sleep(500);   //suspends the execution of Thread for 500 milliseconds
 }
 } 
 catch (InterruptedException e) 
 {
 System.out.println("Child interrupted.");
 }
 System.out.println("Exiting child thread.");
 }
}

public class ThreadDemo 
{
 public static void main(String args[ ] )
 {
 new NewThread(); // create a new thread as we don't want to instantiate object only constructor.
 try
  {
 for(int i = 3; i > 0; i--) 
 {
 System.out.println("Main Thread: " + i);
 Thread.sleep(1000);
 }
 } 
 catch (InterruptedException e) 
 {
 System.out.println("Main thread interrupted.");
 }
 System.out.println("Main thread exiting.");
 }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 3

Child Thread: 3

Child Thread: 2

Main Thread: 2

Child Thread: 1

Exiting child thread.

Main Thread: 1

Main thread exiting.

Thread(Runnable threadOb, String threadName)-readOb is the object of the class which implements the Runnable interface. Here it is the reference to the same class that's why we used this as the reference to same.

void start( )-The new thread will not run until it call it's start() method which is declared within Thread. This method will executes run() method after execution of that method.

public void run( )-Inside this method we can use this Thread and declare variables use classes as same as main thread but main difference is the run will tell the entry point for the Thread and it will end when run() return.

Main Thread will finish last than other threads if vice versa then java run-time system is set to be hanged.

  • Extending Thread

The second way to create Thread is by extending the Thread class as follows

// Create a second thread by extending Thread
class NewThread extends Thread
 {
 NewThread()
{
 // Create a new, second thread
 super("Demo Thread");
 System.out.println("Child thread: " + this);
 start(); // Start the thread
 }
 // This is the entry point for the second thread.
 public void run() 
{
 try 
{
 for(int i = 3; i > 0; i--) 
{
 System.out.println("Child Thread: " + i);
 Thread.sleep(500);
 }
 } 
catch (InterruptedException e) 
{
 System.out.println("Child interrupted.");
 }
 System.out.println("Exiting child thread.");
 }
}
public class ExtendedThread

 {
 public static void main(String args[])
 {
 new NewThread(); // create a new thread
 try 
{
 for(int i = 3; i > 0; i--) 
{
 System.out.println("Main Thread: " + i);
 Thread.sleep(1000);
 }
 } 
catch (InterruptedException e) 
{
 System.out.println("Main thread interrupted.");
 }
 System.out.println("Main thread exiting.");
 }
}

Output:

Child thread: Thread[Demo Thread,5,main]

Main Thread: 3

Child Thread: 3

Child Thread: 2

Main Thread: 2

Child Thread: 1

Exiting child thread.

Main Thread: 1

Main thread exiting.

This Thread also generates the same output as implemented Thread, but main difference is here we are using super("Demo Thread") which passes the name of the string to Thread class which is super class to NewThread class.

public Thread(String threadName)-This is the constructor which takes the name of the thread as a parameter and creates the Thread.

Best Approach

  • Implementing Runnable interface is the best way to create a Thread as in extending a Thread class we can override all the methods in Thread class but we are overriding run() method only which is the same method we have to write in class which implements Runnable interface.
  • By implementing Runnable we can extend any other class what thus class wants. If extend the Thread class we can't extend other classes as in Java we can extend only one class.

Creating Multiple Threads

// Create multiple threads.
class NewThread implements Runnable 
{
 String name; // name of thread
 Thread t;
 NewThread(String threadname) 
 {
 name = threadname;
 t = new Thread(this, name);
 System.out.println("New thread: " + t);
 t.start(); // Start the thread
 }

 // This is the entry point for thread.
 public void run() 
 {
 try 
 {
 for(int i = 3; i > 0; i--) 
 {
 System.out.println(name + ": " + i);
 Thread.sleep(1000);
 }
 } 
 catch (InterruptedException e) 
 {
 System.out.println(name + "Interrupted");
 }
 System.out.println(name + " exiting.");
 }
}
public class MultiThreadDemo 
{
 public static void main(String args[]) 
 {
 new NewThread("One"); // start threads
 new NewThread("Two");
 new NewThread("Three");
 try 
 {
 // wait for other threads to end
 Thread.sleep(10000);
 } 
 catch (InterruptedException e)
  {
 System.out.println("Main thread Interrupted");
 }
 System.out.println("Main thread exiting.");
 }
}

Output:

New thread: Thread[One,5,main]

New thread: Thread[Two,5,main]

One: 3

New thread: Thread[Three,5,main]

Two: 3

Three: 3

One: 2

Two: 2

Three: 2

One: 1

Two: 1

Three: 1

One exiting.

Two exiting.

Three exiting.

Main thread exiting.

results matching ""

    No results matching ""