Java Thread


 

Java Thread

In this tutorial we will discuss about Java Thread.

In this tutorial we will discuss about Java Thread.

Java Thread

In this tutorial we will discuss about Java Thread.

Java Thread :

A thread is light weight java program.JVM permits you to have multiple threads for concurrent execution. Each thread has priority. You can also set priority to threads. Thread having higher priority will execute first and then the other thread having priority less than the higher one.

Life cycle of thread :

Diagram - Here is pictorial representation of thread life cycle.





State of Thread Life cycle -

  • New : This is the state where new thread is created by creating instance of a Thread. It lives in this state until you start the thread.
  • Runnable : when you call start() it enter into the runnable state. In this state thread is ready to run but waiting for the scheduler to select it to run.
  • Running : when thread get the CPU for execution it enters into the running state.
  • Waiting : Sometimes it is need to put some thread on waiting state while the thread waits for another thread to perform a task. For putting your thread into wait state you can call method wait(),sleep(), or suspend().
  • Dead : A thread reached in dead state when its run() method completed.

Thread Priorities: Thread having higher priority, execute first. Java priorities ranges from  MAX_PRIORITY (constant value 10) to
MIN_PRIORITY
(constant value 1).

Thread class provides you 3 priority -

MAX_PRIORITY : It is maximum priority that a thread hold.

MIN_PRIORITY  : It is minimum priority that a thread hold.

NORM_PRIORITY : It is default priority that a thread hold.

Example :


public class SimpleThread extends Thread {
	  private int c = 3;
	  private static int threadC = 0;
	  public SimpleThread() {
	    super("" + ++threadC); // Store the thread name
	    start();
	  }
	  public String toString() {
	    return "Thread"+getName() + ": " + c;
	  }
	  public void run() {
	    while(true) {
	      System.out.println(this);
	      if(--c == 0) return;
	    }
	  }
	  public static void main(String[] args) {
	    for(int i = 0; i <3; i++)
	      new SimpleThread();
	  }
	} 

Output :

Thread1: 3
Thread1: 2
Thread1: 1
Thread2: 3
Thread2: 2
Thread2: 1
Thread3: 3
Thread3: 2
Thread3: 1

Ads