Threading in Java

Introduction

 
Until now, the programs we have discussed so far were sequential ones, i.e. each of the them has a beginning, an execution sequence, and an end. While the program is being executed, at any point of time, there is a single line of execution. One thing that you must note that a thread in itself is not a program, as it cannot run on its own. However it can be embedded with any other program.
 
A thread is a single sequential flow of control within a program.
 
There are many definition of thread some of the A thread is a lightweight process, a thread is a basic processing unit to which an operating system allocates processor time and more than one thread can be executing code inside a process.
 

States of thread

 
1-New-This is a state when a thread is not started. But the thread is created.
 
2-Runnable- This is the execution state of the thread.
 
3-Blocked- This is the state when a thread is waiting for a lock to access an object.
 
4-Waiting-In this state a thread is waiting indefinitely for another thread to perform an action.
 
5-Timed__Waiting. A state in which a thread is waiting for up to a specified period of time for another thread to perform an action.
 
6-Not Runnable- after Runnable states these three states are assumed to be in a not Runnable state. These three states are waiting, Timed_waiting and Terminated.
 
7-Terminated- In this state the thread is dead. 
 

Life Cycle of  a thread

 
thread2.jpg

Crating a thread

 
There are two ways for creating a thread.
 
Method-1 : By extend the Thread class of java.lang package.
 
Syntax
 
class MyThread extends Thread
{
 -----------------;
-----------------;
}
 
The run( ) method has to be Overridden by writing codes required for the thread. The thread behaves as per this code segment.
 
public void run()
{
----------------;
----------------;
}
 
Example- In this Example we are going to create a thread with the help of the extends Thread class.
  1. class MyThread extends Thread  
  2.   {  
  3.     int i;  
  4.     MyThread(int i)  
  5.      {  
  6.       this.i=i;        
     
  7.      }  
  8.     public void run() //this method overrid from thread class  
  9.      {        
     
  10.        while(true)  
  11.           {                  
  12.          System.out.println("abhishek kumar dubey:"+i++);  
  13.          try  
  14.           {  
  15.             Thread.sleep(1500);   // use for break 1500 mili second  
  16.           }  
  17.           catch(InterruptedException e)  
  18.            {  
  19.              System.out.println(e);  
  20.            }  
  21.                  if (i==15 ) // use for terminate the infinite loop  
  22.             {  
  23.            System.out.println(Thread.currentThread());  
  24.            break;  
  25.            }            
     
  26.         }  
  27.       }  
  28.    }    
     
  29.  public class TestThread  
  30.    {  
  31.      public static void main(String []args)  
  32.        {   
     
  33.          MyThread m1=new MyThread(1);    
     
  34.               m1.start();     // for start thread     
     
  35.            System.out.println(Thread.currentThread());  
  36.          }  
  37.    } 
     
Output:
 
thread1.jpg
 
Method :2 By Implements Runnable Interface.
 
Note- If you make a thread by using Runnable Interface then it must override the run() method.
 
public MyThread implements Runnable { 
-----------
-----------
public void run() { 
------
------
 }
}
 
Example-
  1. import java.lang.*;  
  2.   
  3. class Runner1 implements Runnable {  
  4.     int i;  
  5.     public void run()      //this method overrid from Runnable interface must be,fuctionality as per reqairements  
  6.     {  
  7.         i = 0;  
  8.         while (true) {  
  9.             System.out.println("Runner_first" + i++);  
  10.             if (i == 10)  
  11.                 break;  
  12.         }  
  13.     }  
  14. }  
  15. class Runner2 implements Runnable {  
  16.     int i;  
  17.     public void run() {  
  18.         i = 0;  
  19.         while (true) {  
  20.   
  21.             System.out.println("Runner_second" + i++);  
  22.             if (i == 10)  
  23.                 break;  
  24.         }  
  25.     }  
  26. }  
  27. public class ThreadDemo {  
  28.     public static void main(String[] args) {  
  29.         Runner1 r = new Runner1();  
  30.         Thread t = new Thread(r);  // I M P  
  31.         /*from here run() method call which is override in Runner class*/  
  32.         t.start();           // for start thread 4 execution  
  33.         Runner2 r1 = new Runner2();  
  34.         Thread t1 = new Thread(r1);  
  35.         /*from here run() method call which is override in Runner class*/  
  36.         t1.start();  
  37.     }  
  38.  
Output
 
runnable-thread 
 

Summary

 
In this article, we learned about Threading in Java and creation of threads in our Java program.
 
Resource
 
A Complete MultiThreading Tutorial in Java