Thursday 27 September 2012

Thread Complete guid

Java thread complete guid


Complete reference  of java thread

1.       Introduction
        A thread is a flow of control within a program . Thread is a sequential path of code execution with in a program .Each thread has its own local variable and programing counter and life cycle.  Thread sharing the same address space means that share instance variables , not local variables.
                Process:- A process is an instantce of computer program that is execute sequentially. It is a collection of instruction which are execute simultaneously at the run time . several process may cotain in a same program . process consis of memeory space allocated by the operation system. It remain running  util all the non daemon thread are done executing.
                Thread:- thread is light weight process which within a program and perform a sepcial task. Several thread may contain in a process. Sigle thread process contain only one thread but in multi thread process contain more than one thread within a process.
2.         Main thread
 Main()  method runs in a one thread , this thread is konow as main thread.of main thread create child thread program will keep runing util the all thread have complete its execution. 
3.       Life cycle of a thread
Different state of thread :-


                New state :- After the creations of thread instance and before  the invocation of start() method .thread concider as not alive
                Ready-to-run state :-  thread start it life from runnable state . after invocation of start() method thread enter to runnable state .in this state thread wait for a turn on the processer . thread can return to this state either running,waiting,sleeping or coming back from blocked state.
                Running state :-  thread currently executiong state that means thread executing. Only way to enter running state is scheduler swelect thread for running  from runnable pool.
                Dead state :- once run method completes thread become dead state. Cant run again.
                Blocked :- waiting the resources that are hold by another thread.


In java (Detail)



New :- remain in this state util program start the thread.
Runnable :- start executing the thread . mean executing start()method in thread
Waiting :- Thread stop there execution temporarly and allow another thread to start execution . once the running thread single to waiting thread to start execution that thread’s state transilate back to running state. 
Timed Waiting :- enter timed waiting state for specific time . thread transilate back to running state when time intervel expired or event it is waiting for is occure .



Multithreading
   Java built-in support for multithreading programming.it contain two or more thread can run concurrently.each thread defaines separate execution path.
Multitasking
                Execute more than one task at a time , task being a progrm.only one cpu involove that switch s from one program to another this switching is so quik that’s why  the apperance of executing all of the programs at same time .

               
Two thread have more than one task(operation) execute cuncorrently , here cpu switch task of each thread.
Advantages of multi threading over multi tasking
 Reduce computation time
Improve performance
Thread share same address space
Context switching between thread is less expensive than process
Cost of communication between threads is relativly low.

Different stage for multi threading

Thread goes to other non-runnable state depend on circumstance.cannot goes to running state from non-runnable state . frist goes to runinng state. Some nonrunnable state.
                Sleeping :- it might be return to runnable state later . if particular event occure.sleep for paricular amount of time.use sleep() to stop the running state of thread.
    Waiting for notification :- Thread send back to runnable state after reciving  notification from another thread.
Blocked on I/O:- wait for completion of blocked operation. Send back to runnable state after availity of resourse
Blocked for joint completion:- come this state because of waiting the completion of another thread.
Blocked for lock acquisition :-come this state because of waiting to acquring the lock of an object .

Java thread methods
currentThread() :- Return object reference to the thread in which it is invoke
getName() :- retrive the name of the thread object or instance.
Start() :- used to start the thread, by calling run Method
Run():- this is entry point to execute thread.
Sleep():-suspend the thread for specific time intervel
isAlive():-determine thread is running or not
activeCount():-  return number of active threads in a particular thread group and all its sub group
interrupt() :- interupt the the thread
yield():- current  thread pause execution and allow other thread to execute.
Join() :- join() / join(long millisecond) these not return until either the thread has completed or it is timed out respectivly.
Thread creation
An objecty of  thread class repersent a thread. 
2 ways of thread creation
1.       Extending the java.lang.thread Class
2.       Implementing the java.lang.runnable interface
In both case override the run() method

Eg: - 
  Class MyThread extends Thread{
                     String s =null;
MyThread (String  s1) {
                                     s=s1;
                                     start();
}
Public void run(){
                System.out.println(s);
}
  }
Public class RunThreadd{
     Public static void main(String arg[]){
                myThread m1 = new Mythread(“”Thread started ….”);
}
}

Implementing  Java.lang.runnaqble interface
Eg:-  Class MyThread implements runnable{
                Thread  t;
                String s =null;
MyThread(String s1){
                s= s1;
                t =new Thread(this);
                t.start();
}
Public void run(){
                System.out.println(s);
}
}
Public  Class Runnable {
                Public static void main(String arg[]) {
                                MyThread m = new  MY=ythread(“thread statrted…..”)
                }
}

Implementation of runnable interface is better :-
1.       Can extend another class .
2.       Can avoid the overhead of thread class which can be excessive
Thread Constructors :-
        Thread(), thread(String) , thread(Runnable),thread(Runnable,String),Thread(ThreadGroup,String) , Thread(ThreadGroup,Runnable) , Thread(ThreadGroup,Runnable,String) , Thread(ThreadGroup,runnable,String,long)
                ThreadGroup :- reperesent a gruoup of thread.it show in hierarchical manner . root thradGroup can contain all other  threadGroup nad thread each subgroup contain other group and thread. Threads can access only belonging thread group.
When new threadGroup is created it added member of existing thread group.
If thread X in group1 aand execute the code
ThreadGroup group2 = new ThreadGroup(group2);
Group2 2 it created under group1.
Change default parent group :- ThreadGroup group2 =n ew ThreadGroup(group2,group3);
Here newly formed group under group2
Functions
getName():-return name of particular group
getParent():- return parent threadGroup
activeGroupCount():- number of active threadGroup in particular threadGroup and all iths subgroup.
getThreadGroup():-  return thread group of a particular thread.

Creating multiple thread
                At the time of execution of the program all threads are registeed with the thread scheduler and cpu scheduler executes them one by one .
Different method for creating multi thread application
Exstend thread class
Implement Runnable interface
Class MyThread exstends Thread {                                 
                Mythread  ( String s) {
                Super(s);
                Satrt();
}
Public void run(){
                For(int i=0;i<5;i++) {
                                Syso(“thread name : ”
+Thread.currentThread().getName());
Try{
                Thread.sleep(1000);
}catch (Exception e){
}
}
Public Class Multithread {
                Public statyic void main(String args[]){
Syso(“Thread name:”+Thread.currentthread().
getName);
Mythread m1 = new Mythread(“My thread  1”);
Mythread m23 =new Mythread(“My thread 2”);
}
}
Class MyThread implements runnable {
         Thread t;  
         Mythread (String s){
                       t = new Thread(thuis, s);
                     t. Start();
            }
            Public void run() {
                      For(int i=0;i<5;i++){
                          Syso(“Thread name :”+Thread.currentThread().getName());
                            Try{
                                    Thread.sleep(1000);
                             }catch (Exception e){
                             }
                       }
             }
            Public class MultiThread {
                     Public static void main(String args[]){
                         Mythread m1 = new Mythread(“Mythread 1”)
                         Mythread m2 = new  Mythread(“My thread 2”)
              }
             }
}

Thread Priorities
       Thread scheduler use thread priorities in the form of integer value to each of its thread to determine the execution schedule of threads. Thread goes to ready to run state based on priority value. Thread scheduler provide cpu time to thread ofhiger priority during ready-to-run sate.
Priority integer value from(1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY)) . default 5(Thread.NORM_PRIORITY).
setPriority() :-To set priority value to a thread
getPriority() :- to get priority value from thread.

When thread is created it inherite the priority of its parent thread. Higher priority thread select for exection.use preemptive schedule algorithm(If the new thread has a higher priority then current running thread leaves the runnable state and higher priority thread enter to the runnable state.) . if two thread with same priority roun-robin algorithum (A running thread is allowed to be execute for the fixed time, after completion the time, current thread indicates to the another thread to enter it in the runnable state.)is applied

Deadlocak
    Deadlock is infinit waiting  for resource. Athread is waiting for an object that hold by second thread and this second thread waiting for object that hoold by frist thread. This situvation is known as deadlock.

  Here cpu this ideal no one thread executed util the holding up resource are free.
Dead locak example :-

      Class MyThread extends Thread {
                String  s1;
                String  s2;
                MyThread (String s1,String s2) {
                                This.s1 = s1;
                                This.s2 = s2;
                                Start();
                }
Public void run(){
                While (true){
                                Sychronized(s1){
                                                Sychronized(s2){
                                                                Syso(s1+s2);
                                                }
                                }             
                }
                }
}

Class Mythread2  extend Thread {
                String s1;
                String s2;
MyThread2(String s1,String2){
This.s1 =s1;
This.s2=s2;
Start();
}
Public void run(){
                While(true){
                                Sychonized(s2){
                                                Sychronized(s1){
                                                                Syso(s2+s1);
}
}
}
}
}

public static void main(string arg[] ){
                                String s1 =”dead”;
                                String s2 = “Lock”;
MyThread m1 = new Mythread(s1,s2);
Mythread2 m2 = new Mythread2(s1,s2);
                }
               
                               
     }

Rules for avoiding dead lock :-
1.       Simplest way to avoid dead lock is follow the heuristic that a synchronized method should never call another synchronized method. This not offern partical.
2.       Allow a top level class to handle the synchronization for all the method of the classes it call . only the method of top level class are synchronized freeing the lower order method do not worry about sychoronization
3.       Make sure locks are always acquired in the same order . this is best solution . very difficult to sketch the locking order . so you can ensure that you are getting and releasing locks in the best order .

Lock starvation.
  It means thread waiting for lock grab long time . because another thread already grab the lock for entire lock time.

Lock acquisition doesn’t queue. Threads don’t check other threads trying to also acquire locks.
Releasing a thread does not affect thread scheduling .processor is responsible for thread scheduling .

Lock starvation happening due to :-

                Multiple threads compete for the same lock
                Important result can occur during this time period
Thread all have same priority
Processor is using round robin scheduling

  

Sychronized Thread
Independed  thread are known as asynchronous thread. Problems of asychronous thread
                Two or more thread share the same resources only one can access the resource at a time
Two thread access the same data . one try to read and one trying write . some inconsitacy will happened . two avoid this java use monitor also known as semaphore by using sychroniozed . this is type of locking only one thread is in critical region once the thread is in critical section no ther thread can enter to that crtical region. So another thread will have to wait for entering critical region.

Synatx:- sychronized (object) {
                                // statement to be sychoronized
                 }

Lock :-
 Lock refers to access granted to a particular thread that can access the shared resources. At a time only one thread can hold the lock.every object has built in lock that is usefull when object has sychoronized method code . mean only one thread can access the resource guarded by the object lock.

                                Only methods or blocks can be sychoronized . A class and variable cannot be sychronized .
                                Each object has just one lock
                                Class can have both sychronized and non syschoronized method
                                 Two thread wants to execute a same syachoronized method in same instance class , only one thread can execute the method at a time
                                Mutiple thread can  access the class’s non sychoronized methods. If your application really not needed sychoronization avoid it beacase it may cause deadlock so should be carefull about syschoronize not to overuse it.
                                Thread hold its lock even it goes to sleep
                                Thread can aquire more than one lock.
                                Construcuctor can not be suchoronized .
Sychoronized methods
If any method want to execute the sychoronize method frist it has to obtain the object lock.if lock is already held then calling thread has to wait.
Example code :-
                                Class Share extends Thread {
                                                Static String msg[] = {“this”,”is ”,”a”,”sychoronized”, “variable”};
                                                Share(String threadName){
                                                                Super(threadName )
}
                                                Public void run(){
                                                                Display(getName());
                                                }
                                                Public sychronize display(String threadN){
                                                                For(int  i=0;i<=4;i++)
                                                                                Syso(ThreadN+msg[i]);
                                                                Try{
                                                                                This.sleep(1000);
                                                                }Catch(Exception e){
                                                                }
                                                }
                                }

                                Public calss sycThread{
                                                Public static void main(String[] args){
                                                                Share t1 = new Share(“Thread One: ”)
                                                                T1.start();
                                                Share t2 = new Share(“Thread Two”);
                                                T2.start();
                                                }
                                }

Sychronize block(statement)
                                Sychoronized  satements must specify the object that provides the native lock.
Example code :-  Class share extends thread{
                                                Static String msg[] = {“This”, “is”,”a”,”Sychoronized”, “variable”};
                                                Share(String threadName){
                                                                Super(threadName);
                                                }
                                                Public void run(){
                                                                Display (getName());
}
Public  void display(String ThreadN){
                Sychronized (this){
                                For(int i=0;i<=4;i++)
                                                Syso(theradN+msg[i]);
                                Try{
                                                This.sleep(1000);             
                                }catch (Exception e){}
                }
}
}
Public calss synstatement {
                Public static void main (String[] args) {
                                Share ti = new Share(“thread one : ”);
                                T1.start();
Share t2 = new Share(“thread Two: “);
T2.start();
                }
}
 Inter-thread Communication
                        Inter-thread communication reduce cpu’s idle time. For inter-thread communication implemented by some methods.these methods defined in “java.lang” package and can only called with in sychronized code .

Methods
 Description
Wait()
Called thread to give up the monitor and go to sleep until some other thread enters the same monitor and call method notifyAll()
Notify()
It call first thread that call wait() on the same object
notifyAll()
Wake up all the thread that called wait()on the same object. Highest prority thread will run first .


Daemon Thread
  Any thread can be daemon thread .it like service provider for others threads or object running in same process as the daemon thread. Used for back ground supporting tasks. If normal thread are not running and remaining thread are daemon threads then interpreter exits.
                                    SetDaemon(true/false) :- specify that thread is daemon thread
                                    Public Boolean isDaemon(): this method used to determine the thread is daemon thread or not .

Locking

Building your own locking class(Mutex)
                        Mutex object serve the locking mechanism.many os implement mutex lock as threading locking mechanisum.in java every object contain a lock . built in in object calss.

                        Example code:- public class buzyLocj{
Protected Thread buztyLock = null;
Protected int lockCount = 0;
Public synchronized void getBusyLock(){
            While(!tryGetBuzyLock())
                        Try {
                                    Wait();
                        }catch(exception ignored){}
}
}

Public synchronized tryGetBuzyLock(){
            If(busylock == null){
                        buzyLock = thread.currentThread();
                        lockCount = 1;
                        return true;
                }
            If(buzyLock == Thread.currentThread()){
            If(buzyLock == null){
lockCount++;
return true;
            }
Return false;

}’
Public sychoronized void freeLockFlag(){
            If(getbuzyLockOwner() == tread.currentThread()){
                        LockConunt--;
                        If(lockCount == 0){
                        BUZYlOCK == 0;
Notify();
}

                        }
}public sysnchronized Thread getBuzyLockOwner(){
            Return buzyLock
   }
}
Thread safe
Two separate thread can access the control at the same time without developer can worry about the threads interface with one another.
OptimizeIt is invaluable tool for thread checking