THREAD LIFE CYCLE

Thread Life Cycle

Naming Convention
Thread Life Cycle

Explanation:

  • start() method make new born state to active

  • No thread directly goes to Running state , It first go to Runnable state then go to running state

  • Once thread finishes the task, normally it goes to death state

  • But if we want to kill the thread before completion of execution use stop() method But it is not normal death. We forcefully or explicitly use stop()

  • If we want to kill any thread forcefully we can call stop() method for that corresponding thread

  • normally if any thread completes the given task then it will go to the death state automatically it’s called as ”normal death”

  • yield() :: Forcefully done running state to runnable state use this method

Note
  • If we are having more than two threads i.e. 4. But 4 threads are needed database connection , but based on our requirement user provide two connections only because of performance issue

  • But we are having 4 threads, at a time 2 threads use database connection. So remaining 2 are under completely waiting. So to increase the performance remaining two threads are forcefully send to waiting state until database connection is released

if we want to bring any thread from active state to waiting state. We have 3 ways-

  • sleep(long int)

  • wait()

  • suspend()

  • sleep(long int):

    It is one of the important method inside thread class, it brings thread from active state to blocked/waiting state with specified time period. Time will be measured in millisec. Once time period is completed then no need to call again to join in runnable state. It will come automatically.

  • wait():

    wait() is one of the important method in thread class. But it is inherited from Object class and it is not specific to Thread class. By using wait() method we can bring the thread from active to blocked state. Here there is no time limit for blocked state thread if any thread comes to the blocked state by using wait() method it won’t goes to active state automatically ”until unless another thread or child thread which is in active state invoke notify() (or) notifyAll()”

    If more than one thread went to the blocked state through wait() method then if we invoke notify() only one thread will come from blocked state to active state remaining are under blocked state. Here /’+++there is no guarantee which thread comes to the active state by using notify()

  • notifyAll():

    if we want to bring all threads from blocked state to active state it’s better to use notifyAll() method

  • suspend():

    It is one of the deprecated/native/older method because it is part of JDK 1.2 version inside thread class. Once any method went to blocked state by using suspend() it won’t come back to active state ”until unless another thread invoke resume() method which is under active state”

  • Note
    • Not advisable to use.

Example 1:


        
               package com.sdj.pack1;
               class Life extends Thread
               {
                  public void run()
                 {
                     for(int i=0;i<30;i++)
                     {
                        System.out.print(this.getName());
                        if(i%10==0)
                        {
                           System.out.println("i am going to sleep");
                           try
                           {
                              sleep(2000);
                           }
                           catch(InterruptedException e)
                           {
                              e.printStackTrace();
                           }
                        }
                     }
                  }
               }
               public class ThLifeCycle
               {
                  public static void main(String[] args)
                  {
                     Life a=new Life();
                     a.start();
                     //a.join();
                     System.out.println("main end");
                  }
               }        

   Output:

main end Thread-0 i am going to sleep Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 i am going to sleep Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 i am going to sleep Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0 Thread-0

Explanation:

  • If any thread is in sleep mode then if we want to perform any operation on that thread it can’t respond.

  • If any thread try to interrupt another thread which is under sleep state then we get InterruptedException

join():

It will give one checked Type exception i.e. InterruptedException. If we want to wait parent thread until child thread task has to be finished then we can call “join()” on corresponding child thread object

  • interrupted() and isInterrupted():

    If we want to interrupt any thread by another thread we can use interrupted() method. If one thread sends interrupted msg or event to the another thread then it will receive that interrupted msg or event. Iff it is in active state else we will get one InterruptedException

    If we want to find out corresponding thread is in interrupted or not in interrupt event we can go for isInterrupted().

    isInterrupted() and isInterrupted():

    isInterrupted() returns Boolean value as output i.e. true/false. If corresponding thread receives interrupted event it return true else false. We can’t interrupt any thread which is under sleep state or wait mode orif it is inside blocked state. Even if we try to interrupt we will get exception. .

Example 2:


        
                  package com.sdj.pack1;
                  class MyThread1 extends Thread
                  {
                     public void run()
                     {
                        int i=0;
                        if(!this.isInterrupted())
                        {
                           System.out.println(" i am not interrupted");
                           System.out.println(i++);
                           if(i==20)
                           {
                              try
                              {
                                 sleep(200);
                              }
                              catch (InterruptedException e)
                              {
                                 e.printStackTrace();
                              }
                           }
                        }
                     }
                  }
                  public class ThInterrupted
                  {
                     public static void main(String[] args)
                     {
                        MyThread1 t=new MyThread1();
                        t.start();
                        int i=10;
                        while(i>0)
                        {
                           t.interrupt();
                           t.isInterrupted();
                        }
                     }
                  }    
  • How to convert daemon threads:

    We can’t create daemon threads directly. But we can convert user threads to daemon threads but vice versa not possible. In thread class there is a method setDaemon() it takes Boolean value as input to the setDaemon() then it will create thread as daemon thread. If we pass Boolean value as false to setDaemon() it will create thread as user thread. By default it will take false value.

    setDaemon() method should call before start() method. If we call after start() method we will get exception IllegalThreadStateException.

  • isDaemon():

    If we want to find created thread as daemon thread or not, then we can use isDaemon(). It will return Boolean value. If current thread is user type it will return false value if current thread is daemon type it will return true value.

Example 3:


        
                  package com.sdj.pack1;
                  class Daemon extends Thread
                  {
                     public void run()
                     {
                        System.out.println("is am daemon type true /false::"+ this.isDaemon());
                     }
                  }
                  public class ThDaemon
                  {
                     public static void main(String[] args)
                     {
                        Daemon d=new Daemon();
                        d.setDaemon(true);
                        d.start();
                        Daemon d1=new Daemon();
                        d1.start();
                        /* d1.setDaemon(false); */
                        Daemon d2=new Daemon();
                        d2.setDaemon(false);
                        d2.start();
                     }
                  }        

   Output:

is am daemon type true/false::true is am daemon type true/false::false is am daemon type true/false::false

Example 4:


        
               package com.sdj.pack1;
               class Daemon1 extends Thread
               {
                  public void run()
                  {
                     int i=0;
                     do
                     {
                        System.out.print(“\t”+i);
                        i++;
                     } while (i<50);
                  }
               }
               public class ThDaemon1 
               {
                  public static void main(String[] args) 
                  {
                     Daemon1 d1=new Daemon1();
                     d1.setDaemon(true);
                     d1.start();
                     Thread mainThread=Thread.currentThread();
                     System.out.println(mainThread.getName());
                     System.out.println(mainThread.isDaemon());
                     System.out.println("main thread is end");
                     try
                     {
                        d1.join();
                     }
                     catch(InterruptedException e)
                     {
                        e.printStackTrace();
                     }   
                  }            
               }        

   Output:

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 main false main thread is end

Explanation:

    Daemon threads depends on parent life time i.e. main. Once main thread finish their execution immediately it will go to the death state. Then after that daemon child thread also go to death state if their task is finished or not.

    So to avoid this drawback we use join() method by the child reference variable. Once we call join() method parent will be waiting until child task gets completed.

Example 5:


        
               package com.sdj.pack1;
               class Test
               {
                  void m1(String s)
                  {
                     m2(s);
                  }
                  void m2(String s1)
                  {
                     m3(s1);
                  }
                  void m3(String s2)
                  {
                     int i=Integer.parseInt(s2);
                     System.out.println(i);
                  }
               }
               class ThreadWait extends Thread
               {
                  public void run()
                  {
                     System.out.println("inside run");
                     Test t1=new  Test();
                     t1.m1("abc");
                     System.out.println("my thread end");
                  }
               }
               class MyThread2 extends Thread
               {
                  public void run()
                  {
                     System.out.println("my thread run");
                     Test t1=new Test();
                     t1.m3("123");
                  }
               }
               public class ThDaemon2 
               {
                  public static void main(String[] args) 
                  {
                     ThreadWait t1=new ThreadWait();
                     t1.start();
                     MyThread2 t2=new MyThread2();
                     t2.start();
                     System.out.println("main thread end");
                  }
               }        

   Output:

inside run main thread end my thread run 123

    Exception in thread "Thread-0"java.lang.NumberFormatException:For input string:"abc"
    at java.lang.Integer.parseInt(Unknown Source) at com.sdj.pack1.ThreadWait.run(ThDaemon2.java:24)


    (or)

    Exception in thread "Thread-0" java.lang.NumberFormatException: For input string: "abc"
    at java.lang.Integer.parseInt(Unknown Source)
    at com.sdj.pack1.Test.m3(ThDaemon2.java:14)
    at com.sdj.pack1.Test.m2(ThDaemon2.java:10)
    at com.sdj.pack1.Test.m1(ThDaemon2.java:6)
    at com.sdj.pack1.ThreadWait.run(ThDaemon2.java:24)


                                main thread end
                                my thread run
                                123

                            

Explanation:

  • Exceptions are thread based if not it is entire execution based. Once stack is separated, then even if we get exception then it is suitable only for child stack memory only, means that threads terminate only.

Exception ducking:

  • Exception ducking will happen only for specific stack trace means within one thread space. If child thread receives any exception i.e. unhandled exception it will propagate only child thread execution stack trace. It won’t propagate or it will not effect to main thread execution.

  • Here ThreadWait receives one unhandled exception i.e. NumberFormatException. After that statement threadWait can’t go forward it will go immediately to death state. But it will not effect to the main thread or MyThread. Why because every thread has their own stack track

  • Note
    • Exceptions are thread based (or) specific to one stack execution.

Example 6:


        
               package com.sdj.pack1;
               class ObjPerson
               {
                  int age;
                  String name;
                  void setObjPerson(int age,String name)
                  {
                     this.age=age;
                     this.name=name;
                  }
                  public String toString()
                  {
                     return "name:"+name+"::age::"+age;
                  }
               }
               class Thread1 extends Thread
               {
                  ObjPerson p;
                  public void run()
                  {
                     p.setObjPerson(23, "measum");
                  }
                  public Thread1(ObjPerson p1) 
                  {
                     p=p1;
                  }
               }
               class Thread2 extends Thread
               {
                  ObjPerson p;
                  public void run()
                  {
                     p.setObjPerson(22, "jayaram");
                  }
                  public Thread2(ObjPerson p1) 
                  {
                     p=p1;
                  }
               }
               public class ThObjLock 
               {
                  public static void main(String[] args) 
                  {
                     ObjPerson p=new ObjPerson();
                     p.setObjPerson(24, "sankar");
                     Thread1 t=new Thread1(p);
                     Thread2 t1=new Thread2(p);
                     t.start();
                     t1.start();
                     System.out.println(p);
                     System.out.println(t.p);
                     System.out.println(t1.p.age);
                     System.out.println(t1.p.name);
                  }
               }        

   Output:

name:sankar::age::24 name:sankar::age::24 24 sankar (Or) name:jayaram::age::22 name:jayaram::age::22 22 jayaram


  • Object Lock and Class Lock:

    In java every object has one object lock and every class have class lock.

    • We can achieve object lock through synchronization in java
    • We can achieve class lock through static synchronization in java
    • Through synchronization we can achieve thread safety