Saturday, 19 July 2014

THREAD

Actually Thread is an Operating System concept, this provide efficient performance through "Parallelism or Concurrency". Parallelism /Concurrency meaning doing many work at the same time without waiting for completion of one another. Thread give us multitasking.



Thread provide mechanism  to perform another work without waiting for completion to another work. 
Thread are also called "Light weight Process". Each Thread shall reside in the Process and no one Thread are outside the process. Every Thread have their own Stack memory, heap memory,register  and program counter .

In above there is symbol represent the Thread.
Thread provide synchronization : each thread shared data of other thread in same process.One thread can read, write or change another thread's data.

Types of Thread

There are two types of Thread
  1. User Level Threads -- User managed threads
  2. Kernel Level Threads -- Operating System managed threads acting on kernel, an operating system core.
But in this topic I haven't discuss because it's require 100 page to explain this operating system concept.




Life Cycle of a Thread (Thread States)

A thread have five state and it's have only one state at a time
A thread can be in one of the five states in the thread. According to sun, there is only 4 states new, runnable, non-runnable and terminated. There is no running state. But for better understanding the threads, we are explaining it in the 5 states. The life cycle of the thread is controlled by JVM. The thread states are as follows:
  1. New
  2. Runnable
  3. Running
  4. Waiting (Blocked)
  5. Dead

1) New

When you create the instance of Thread Object.

2) Runnable

When you invoke the start() method thread object ,but scheduling algorithm have not been selected this thread.

3) Running

It's start it's working and get scheduled by scheduling algorithm of operating system 

4) Waiting

This is the state when the thread is still alive, but is currently not eligible to run.

5) Dead

A thread is in dead state when object of thread become out of scope and garbage collector sweep it from system outsources.


Implementation Thread in JAVA

You can implement Thread in Java be two ways
  1. extends Thread class
  2. implement runnable interface
Here are code example

public class ThreadA implements Runnable {
    public void run() {
     //Code
    }
}
 public class ThreadA extends Thread {
    public void run() {
     //Code
    }
}





you can start thread by just invoking start() method to make it into running state.
  
ThreadA myThread=new ThreadA();
myThread.start();


No comments:

Post a Comment