SlideShare uma empresa Scribd logo
1 de 29
Thread Lifecycle and Thread Methods




                                      1
Objective


On completion of this period, you would be
able to learn

• Thread Lifecycle
• Thread methods
• Example Programs




                                             2
Recap

• In the previous class we have seen how to set the
  priorities of threads
• Thread class provides 3 constants for setting
  priorities
  • Thread.NORM_PRIORITY
  • Thread.MAX_PRIORITY
  • Thread.MIN_PRIORITY
• Thread class also provides two methods
  • setPriority()
  • getPriority()




                                                      3
Thread Life Cycle

• Just like a Process has life cycle
   • Thread also has a life cycle
   • A Thread under goes different states while it is
     executing

• We know the process state diagram
   • It is used to represent the life cycle of a process
   • Similarly the life cycle of a thread can be represented by
     thread state diagram



                                                              4
Thread Life Cycle
                                     Contd . . .


• A Thread can be in one of the following states
  •   New born
  •   Running
  •   Ready to run
  •   Blocked
  •   Dead




                                                   5
Thread Life Cycle
                                                               Contd . . .
The following figure shows the life cycle of a thread
                           New born
                           New born
                   start()                            stop()


                                                      stop()
                                         Ready to
                 Running                                            Dead
                                                                    Dead
                                           Run
                              yield()

              suspend()                 resume()
              wait()                    notifyAll()     stop()
              sleep()                   notify()

                             Blocked
                             Blocked

    Fig. 36.1. Thread lifecycle – state transition diagram
                                                                             6
Thread Life Cycle
                                              Contd . . .

• When a thread object is created, it enters new born state
• start() method changes the state to either running or
  ready to state
• suspend(), sleep()or wait() methods moves the thread to
  a blocked state
• resume(), notify() or notifyAll() methods moves the
  blocked thread to running/ready to run state
• A call to stop() method kills the thread
• A running thread can give away the control of execution
  to another thread by calling yield() methods


                                                              7
Methods of Thread
•Some of the methods of the Thread class are
   • start()
   • stop()
   • suspend()
   • resume()
   • wait()
   • notify()
   • notifyAll()
   • isAlive()
   • yield()
   • join()


                                               8
isAlive() method

• The signature of this method

         public final boolean isAlive()


  • Returns true if the thread is not dead (run has not
    completed)
  • Returns false if the thread is dead




                                                          9
join() method

• The signature of join() method

           public final void join();
           public final void join(long t);
  • Calling thread waits for thread receiving message to die
    before it can proceed
  • No argument or 0 millisecond argument means thread
    will wait indefinitely
     • Can lead to deadlock/indefinite postponement



                                                               10
Example Program

class NewThread implements Runnable {
 String name; // name of thread
 Thread t;
 NewThread(String threadname) {
   name = threadname;
   t = new Thread(this, name);
   System.out.println("New thread: " + t);
   t.start(); // Start the thread
 }


                                             11
Example Program
                                  Contd . . .
public void run() {
    try {
      for(int i = 5; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
                System.out.println(name + "
    interrupted.");
    }
    System.out.println(name + " exiting.");
  }
}
                                                12
Example Program
                                                       Contd . . .

class DemoJoin {
 public static void main(String args[]) {
   NewThread ob1 = new NewThread("One");
   NewThread ob2 = new NewThread("Two");
   NewThread ob3 = new NewThread("Three");
   System.out.println("Thread One is alive: “ +
   ob1.t.isAlive());
   System.out.println("Thread Two is alive: “ +
   ob2.t.isAlive());
   System.out.println("Thread Three is alive: “ +
   ob3.t.isAlive());                      Use of isAlive()
                                             At this moment all threads
                                                                          13
                                             are alive and return true
Example Program
                                                            Contd . . .
try {
      System.out.println("Waiting for threads to finish."); main() thread waits
      ob1.t.join();                                         until all threads finish
                                                            their work
      ob2.t.join();
      ob3.t.join();                                        As threads have
    } catch (InterruptedException e) {                     finished,
                                                           isAlive() returns false
      System.out.println("Main thread Interrupted");
    }
    System.out.println("Thread One is alive: “ + ob1.t.isAlive());
    System.out.println("Thread Two is alive: “ + ob2.t.isAlive());
    System.out.println("Thread Three is alive: “ + ob3.t.isAlive());
    System.out.println("Main thread exiting.");
  }
}                                                                                    14
Example Program
                           Contd . . .
Output




                                         15
suspend() method

• The signature of this method

        public final void suspend();


  • If the thread is alive, it is suspended and makes no
    further progress unless and until it is resumed




                                                           16
resume() method


• The signature of this method

       public final void resume();

  • If the thread is alive but suspended, it is resumed
    and is permitted to make progress in its execution.




                                                          17
Example Program

class NewThread implements Runnable {
 string name; // name of thread
 Thread t;

 NewThread(String threadname) {
   name = threadname;
   t = new Thread(this, name);
   System.out.println("New thread: " + t);
   t.start(); // Start the thread
 }

                                             18
Example Program
                                                Contd . . .
public void run() {
    try {
      for(int i = 10; i > 0; i--) {
        System.out.println(name + ": " + i);
        Thread.sleep(200);
      }
    } catch (InterruptedException e) {
      System.out.println(name + " interrupted.");
    }
    System.out.println(name + " exiting.");
  }
}                                                             19
Example Program
                                       Contd . . .
class SuspendResume {
 public static void main(String args[]) {
   NewThread ob1 = new NewThread("One");
   NewThread ob2 = new NewThread("Two");
   try {
     Thread.sleep(1000);
     ob1.t.suspend();
     System.out.println("Suspending thread One");
     Thread.sleep(1000);
     ob1.t.resume();
     System.out.println("Resuming thread One");
     ob2.t.suspend();
     System.out.println("Suspending thread Two");
                                                     20
Example Program
                                             Contd . . .


 Thread.sleep(1000);
  ob2.t.resume();
  System.out.println("Resuming thread Two");
} catch (InterruptedException e) {
  System.out.println("Main thread Interrupted");
}




                                                           21
Example Program
                                                   Contd . . .
          // wait for threads to finish
        try {
              System.out.println("Waiting for threads to
        finish.");
          ob1.t.join();
          ob2.t.join();
        } catch (InterruptedException e) {
          System.out.println("Main thread Interrupted");
        }
        System.out.println("Main thread exiting.");
    }
}                                                                22
Example Program
Output
                           Contd . . .




                                         23
Summary
• In this class we have discussed
  • The life cycle of thread
  • The state transition diagram
  • The thread methods
     • isAlive()
     • join()
     • suspend()
     • resume()
• In the next lesson we look at the concept of
  synchronization

                                                 24
Quiz

1. A suspended thread goes to ready state by
   calling

  A.   start() method
  B.   ready() method
  C.   resume() method
  D.   None




                                               25
Quiz   Contd..

2. Which of the following method changes the
  state of the thread to blocked state ?

  A.   stop()
  B.   suspend()
  C.   notify()
  D.   notify All()




                                               26
Quiz   Contd..

3. What is the return type of isAlive() method ?

   A.   int
   B.   float
   C.   double
   D.   boolean




                                                   27
Quiz     Contd..

4. Which of the following method kills the
  thread ?

  A.   kill()
  B.   stop()
  C.   end()
  D.   None




                                             28
Frequently Asked Questions

1. Draw and explain the state-transition diagram of
   thread
2. What are the different states the thread enters
   while it is executing ?
3. Write the syntax of using isAlive(), join()
   methods
4. Write the syntax of using suspend(), resume()
   methods



                                                      29

Mais conteúdo relacionado

Mais procurados

Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded ApplicationsBharat17485
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introductioncaswenson
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsShinpei Hayashi
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-threadjavaicon
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxSoumen Santra
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)choksheak
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronizationcaswenson
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matterDawid Weiss
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency beginingmaksym220889
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizersts_v_murthy
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped LockHaim Yadid
 
Mc Squared
Mc SquaredMc Squared
Mc Squaredsganga
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-javaaalipalh
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 

Mais procurados (19)

Internet Programming with Java
Internet Programming with JavaInternet Programming with Java
Internet Programming with Java
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Understanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring EffectsUnderstanding Source Code Differences by Separating Refactoring Effects
Understanding Source Code Differences by Separating Refactoring Effects
 
Threads in java
Threads in javaThreads in java
Threads in java
 
Life cycle-of-a-thread
Life cycle-of-a-threadLife cycle-of-a-thread
Life cycle-of-a-thread
 
Threads Advance in System Administration with Linux
Threads Advance in System Administration with LinuxThreads Advance in System Administration with Linux
Threads Advance in System Administration with Linux
 
Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)Advanced Introduction to Java Multi-Threading - Full (chok)
Advanced Introduction to Java Multi-Threading - Full (chok)
 
Learning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and SynchronizationLearning Java 3 – Threads and Synchronization
Learning Java 3 – Threads and Synchronization
 
Multi threading
Multi threadingMulti threading
Multi threading
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
Java concurrency begining
Java concurrency   beginingJava concurrency   begining
Java concurrency begining
 
Java synchronizers
Java synchronizersJava synchronizers
Java synchronizers
 
Java 8 - Stamped Lock
Java 8 - Stamped LockJava 8 - Stamped Lock
Java 8 - Stamped Lock
 
Java threading
Java threadingJava threading
Java threading
 
Python multithreading
Python multithreadingPython multithreading
Python multithreading
 
Mc Squared
Mc SquaredMc Squared
Mc Squared
 
Multithreading in-java
Multithreading in-javaMultithreading in-java
Multithreading in-java
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 

Semelhante a Threadlifecycle.36

Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptxRanjithaM32
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.pptssuserec53e73
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptTabassumMaktum
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaMonika Mishra
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVAVINOTH R
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming LanguagesYudong Li
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programmingSonam Sharma
 

Semelhante a Threadlifecycle.36 (20)

Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
Java Multithreading.pptx
Java Multithreading.pptxJava Multithreading.pptx
Java Multithreading.pptx
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Session 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.pptSession 7_MULTITHREADING in java example.ppt
Session 7_MULTITHREADING in java example.ppt
 
Multithreading.pptx
Multithreading.pptxMultithreading.pptx
Multithreading.pptx
 
Thread 1
Thread 1Thread 1
Thread 1
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
Java Week9(A) Notepad
Java Week9(A)   NotepadJava Week9(A)   Notepad
Java Week9(A) Notepad
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Threads
ThreadsThreads
Threads
 
Threads
ThreadsThreads
Threads
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
unit-3java.pptx
unit-3java.pptxunit-3java.pptx
unit-3java.pptx
 
Concurrency in Programming Languages
Concurrency in Programming LanguagesConcurrency in Programming Languages
Concurrency in Programming Languages
 
Thread
ThreadThread
Thread
 
Multithreaded programming
Multithreaded programmingMultithreaded programming
Multithreaded programming
 

Mais de myrajendra (20)

Fundamentals
FundamentalsFundamentals
Fundamentals
 
Data type
Data typeData type
Data type
 
Hibernate example1
Hibernate example1Hibernate example1
Hibernate example1
 
Jdbc workflow
Jdbc workflowJdbc workflow
Jdbc workflow
 
2 jdbc drivers
2 jdbc drivers2 jdbc drivers
2 jdbc drivers
 
3 jdbc api
3 jdbc api3 jdbc api
3 jdbc api
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Dao example
Dao exampleDao example
Dao example
 
Sessionex1
Sessionex1Sessionex1
Sessionex1
 
Internal
InternalInternal
Internal
 
3. elements
3. elements3. elements
3. elements
 
2. attributes
2. attributes2. attributes
2. attributes
 
1 introduction to html
1 introduction to html1 introduction to html
1 introduction to html
 
Headings
HeadingsHeadings
Headings
 
Forms
FormsForms
Forms
 
Css
CssCss
Css
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Views
ViewsViews
Views
 
Starting jdbc
Starting jdbcStarting jdbc
Starting jdbc
 

Threadlifecycle.36

  • 1. Thread Lifecycle and Thread Methods 1
  • 2. Objective On completion of this period, you would be able to learn • Thread Lifecycle • Thread methods • Example Programs 2
  • 3. Recap • In the previous class we have seen how to set the priorities of threads • Thread class provides 3 constants for setting priorities • Thread.NORM_PRIORITY • Thread.MAX_PRIORITY • Thread.MIN_PRIORITY • Thread class also provides two methods • setPriority() • getPriority() 3
  • 4. Thread Life Cycle • Just like a Process has life cycle • Thread also has a life cycle • A Thread under goes different states while it is executing • We know the process state diagram • It is used to represent the life cycle of a process • Similarly the life cycle of a thread can be represented by thread state diagram 4
  • 5. Thread Life Cycle Contd . . . • A Thread can be in one of the following states • New born • Running • Ready to run • Blocked • Dead 5
  • 6. Thread Life Cycle Contd . . . The following figure shows the life cycle of a thread New born New born start() stop() stop() Ready to Running Dead Dead Run yield() suspend() resume() wait() notifyAll() stop() sleep() notify() Blocked Blocked Fig. 36.1. Thread lifecycle – state transition diagram 6
  • 7. Thread Life Cycle Contd . . . • When a thread object is created, it enters new born state • start() method changes the state to either running or ready to state • suspend(), sleep()or wait() methods moves the thread to a blocked state • resume(), notify() or notifyAll() methods moves the blocked thread to running/ready to run state • A call to stop() method kills the thread • A running thread can give away the control of execution to another thread by calling yield() methods 7
  • 8. Methods of Thread •Some of the methods of the Thread class are • start() • stop() • suspend() • resume() • wait() • notify() • notifyAll() • isAlive() • yield() • join() 8
  • 9. isAlive() method • The signature of this method public final boolean isAlive() • Returns true if the thread is not dead (run has not completed) • Returns false if the thread is dead 9
  • 10. join() method • The signature of join() method public final void join(); public final void join(long t); • Calling thread waits for thread receiving message to die before it can proceed • No argument or 0 millisecond argument means thread will wait indefinitely • Can lead to deadlock/indefinite postponement 10
  • 11. Example Program class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } 11
  • 12. Example Program Contd . . . public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } 12
  • 13. Example Program Contd . . . class DemoJoin { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); NewThread ob3 = new NewThread("Three"); System.out.println("Thread One is alive: “ + ob1.t.isAlive()); System.out.println("Thread Two is alive: “ + ob2.t.isAlive()); System.out.println("Thread Three is alive: “ + ob3.t.isAlive()); Use of isAlive() At this moment all threads 13 are alive and return true
  • 14. Example Program Contd . . . try { System.out.println("Waiting for threads to finish."); main() thread waits ob1.t.join(); until all threads finish their work ob2.t.join(); ob3.t.join(); As threads have } catch (InterruptedException e) { finished, isAlive() returns false System.out.println("Main thread Interrupted"); } System.out.println("Thread One is alive: “ + ob1.t.isAlive()); System.out.println("Thread Two is alive: “ + ob2.t.isAlive()); System.out.println("Thread Three is alive: “ + ob3.t.isAlive()); System.out.println("Main thread exiting."); } } 14
  • 15. Example Program Contd . . . Output 15
  • 16. suspend() method • The signature of this method public final void suspend(); • If the thread is alive, it is suspended and makes no further progress unless and until it is resumed 16
  • 17. resume() method • The signature of this method public final void resume(); • If the thread is alive but suspended, it is resumed and is permitted to make progress in its execution. 17
  • 18. Example Program class NewThread implements Runnable { string name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } 18
  • 19. Example Program Contd . . . public void run() { try { for(int i = 10; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(200); } } catch (InterruptedException e) { System.out.println(name + " interrupted."); } System.out.println(name + " exiting."); } } 19
  • 20. Example Program Contd . . . class SuspendResume { public static void main(String args[]) { NewThread ob1 = new NewThread("One"); NewThread ob2 = new NewThread("Two"); try { Thread.sleep(1000); ob1.t.suspend(); System.out.println("Suspending thread One"); Thread.sleep(1000); ob1.t.resume(); System.out.println("Resuming thread One"); ob2.t.suspend(); System.out.println("Suspending thread Two"); 20
  • 21. Example Program Contd . . . Thread.sleep(1000); ob2.t.resume(); System.out.println("Resuming thread Two"); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } 21
  • 22. Example Program Contd . . . // wait for threads to finish try { System.out.println("Waiting for threads to finish."); ob1.t.join(); ob2.t.join(); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } 22
  • 23. Example Program Output Contd . . . 23
  • 24. Summary • In this class we have discussed • The life cycle of thread • The state transition diagram • The thread methods • isAlive() • join() • suspend() • resume() • In the next lesson we look at the concept of synchronization 24
  • 25. Quiz 1. A suspended thread goes to ready state by calling A. start() method B. ready() method C. resume() method D. None 25
  • 26. Quiz Contd.. 2. Which of the following method changes the state of the thread to blocked state ? A. stop() B. suspend() C. notify() D. notify All() 26
  • 27. Quiz Contd.. 3. What is the return type of isAlive() method ? A. int B. float C. double D. boolean 27
  • 28. Quiz Contd.. 4. Which of the following method kills the thread ? A. kill() B. stop() C. end() D. None 28
  • 29. Frequently Asked Questions 1. Draw and explain the state-transition diagram of thread 2. What are the different states the thread enters while it is executing ? 3. Write the syntax of using isAlive(), join() methods 4. Write the syntax of using suspend(), resume() methods 29