SlideShare a Scribd company logo
Java2

An Introduction to Threads
Objectives

   Compare Multitasking and Multithreading
   Define a thread
   Discuss Benefits of multithreading
   Explain how to create threads
   Describe Thread states
   Discuss Thread priorities
   Discuss Daemon thread
                        eACCP 2002/Sem 1/ JPL/
                        Session 6/ 2 of 26
Multitasking Vs Multithreading

   Multitasking is the ability to run one or more
    programs concurrently
   Operating system controls the way in which
    these programs run by scheduling them
   Time between switching of programs is
    minute
   Multithreading is the ability to execute
    different parts of a program called threads,
    simultaneously          eACCP 2002/Sem 1/ JPL/
                          Session 6/ 3 of 26
Thread
   Smallest unit of executable code that
    performs a task
   An application can be divided into multiple
    tasks and each task can be assigned to a
    thread
   Many threads executing simultaneously is
    termed as Multithreading
   Although it may appear that the processes
    are running concurrently, it is not so 1/ JPL/
                         eACCP 2002/Sem
                           Session 6/ 4 of 26
Benefits of multithreading

   Multithreading requires less overhead than
    multitasking
       In multitasking, processes run in their own
        different address space
       Tasks involved in multithreading can share the
        same address space
   Inter-process calling involves more overhead
    than inter-thread communication
                              eACCP 2002/Sem 1/ JPL/
                              Session 6/ 5 of 26
Applications of thread

   Playing sound and displaying images
    simultaneously

   Displaying multiple images on the screen

   Displaying scrolling text patterns or images
    on the screen
                          eACCP 2002/Sem 1/ JPL/
                          Session 6/ 6 of 26
Creating threads (1)

   When Java programs execute, there is
    always one thread running and that is the
    main thread
       It is this thread from which child threads are
        created
       Program is terminated when main thread stops
        execution
       Main thread can be controlled through ‘Thread’
        objects
                                eACCP 2002/Sem 1/ JPL/
                                Session 6/ 7 of 26
Creating threads (2)
   Thread objects can be created in two ways:
       Declare a class that is a sub-class of the class
        Thread defined in java.lang package
               class mythread extends Thread
       Declare a class that implements the Runnable
        interface
               class mythread implements Runnable

   While using applets, Thread class cannot be
    extended. Therefore one has to implement the
    Runnable interface     eACCP 2002/Sem 1/ JPL/
                                   Session 6/ 8 of 26
Creating threads (3)

   To initiate a new thread, we use the start()
    method
       Mythread t = new Mythread();
       t.start();

   When start() method is invoked, a new thread
    of control is created
   It then calls the run() method
                               eACCP 2002/Sem 1/ JPL/
                               Session 6/ 9 of 26
Creating threads (4)
               Example 1 –
                Creating a thread by
                extending the Thread
                class


                      Output




         eACCP 2002/Sem 1/ JPL/
         Session 6/ 10 of 26
Creating threads (5)
               Example2 –
                Creating a thread by
                implementing the
                Runnable interface


                       Output




         eACCP 2002/Sem 1/ JPL/
         Session 6/ 11 of 26
Thread states (1)

   Born – a newly created thread is in a born
    state

   Ready – after a thread is created, it is in its
    ready state waiting for start() method to be
    called

                           eACCP 2002/Sem 1/ JPL/
                           Session 6/ 12 of 26
Thread states (2)

   Running – thread enters the running state
    when it starts executing

   Sleeping – execution of a thread can be
    halted temporarily by using sleep() method.
    The thread becomes ready after sleep time
    expires
                         eACCP 2002/Sem 1/ JPL/
                         Session 6/ 13 of 26
Thread states (3)

   Waiting – thread is in waiting state if wait()
    method has been invoked

   Blocked – when the thread waits for an
    Input/Output operation

   Dead – after the run() method has finished or
    the threads stop() method is2002/Sem 1/ JPL/
                          eACCP called
                           Session 6/ 14 of 26
Different thread states
             New Thread
              (BORN)



              READY



  SLEEPING                SUSPENDED


             RUNNING

WAITING                       BLOCKED

               DEADeACCP    2002/Sem 1/ JPL/
                    Session 6/ 15 of 26
Some methods
                of thread class (1)

   isAlive() – returns true if the thread is alive

   getName() – returns the name of the thread

   start() – used to start a thread by calling the
    method run()
                               eACCP 2002/Sem 1/ JPL/
                               Session 6/ 16 of 26
Some methods
           of thread class (2)
   resume() – to resume the execution of a
    suspended thread

   yield() – causes the currently executing
    thread to temporarily pause and allow other
    threads to execute

   setName(String name) – sets the name of
    the thread to the name that is passed as
                         eACCP 2002/Sem 1/ JPL/
    argument             Session 6/ 17 of 26
Some methods
            of thread class (3)
   join() – waits for the thread to die

   isDaemon() – checks if the thread is a
    Daemon thread

   activeCount() – returns the number of active
    threads

   sleep() – used to suspend a thread for a
    certain period of time eACCP 2002/Sem 1/ JPL/
                           Session 6/ 18 of 26
Conditions preventing
            thread execution

   Thread is:
       Not of highest priority
       Put to sleep using sleep() method
       Suspended using suspend() method
       Thread is waiting because wait() method was
        called
       Explicitly yielded using yield() method
       Blocked for file I/O
                                eACCP 2002/Sem 1/ JPL/
                                Session 6/ 19 of 26
Managing threads (1)
   Priorities for carrying out activities changes at
    times
       eg :Planned to visit museum in the afternoon but
        due to toothache, had to go to doctor
   Similarly while programming, we may have to
    run a thread of higher importance without
    stopping or suspending the current running
    thread
   Thread priorities play an important role in
    such a situation       eACCP 2002/Sem 1/ JPL/
                              Session 6/ 20 of 26
Managing threads (2)

   Thread priorities in Java are constants
    defined in the Thread class
          NORM_PRIORITY         – value is
          MAX_PRIORITY          – value is
          MIN_PRIORITY          – value is
   The default priority is NORM_PRIORITY
   Two methods used to change priority:
       
           setPriority() - changes the thread’s current priority
       
           getPriority() - returns the thread’s priority
                                  eACCP 2002/Sem 1/ JPL/
                                  Session 6/ 21 of 26
Daemon threads (1)
   Two types of threads in Java:
       User threads – created by the user
       Daemon threads – threads that work in the
        background providing service to other threads
         
             e.g. – the garbage collector thread
   When user thread exits, JVM checks to find
    out if any other thread is running
   If the only executing threads are Daemon
    threads, it exits      eACCP 2002/Sem 1/ JPL/
                                   Session 6/ 22 of 26
Daemon threads (2)

   We can set a thread to be a Daemon if we do
    not want the main program to wait until a
    thread ends
   Thread class has two methods to deal with
    Daemon threads:
       public void setDaemon(boolean value) : sets a
        thread to be a daemon thread
       public void isDaemon() : checks if the given thread
        is a daemon thread eACCP 2002/Sem 1/ JPL/
                             Session 6/ 23 of 26
Daemon threads (3)
An example




                        Output




             eACCP 2002/Sem 1/ JPL/
             Session 6/ 24 of 26
Session summary (1)

   When Java programs are executed, there is
    always one thread that is running and that is
    the main thread
   Threads can be used in two ways:
       Declare the class to be a sub-class of the Thread
        class
       Declare a class that implements the Runnable
        interface
                               eACCP 2002/Sem 1/ JPL/
                               Session 6/ 25 of 26
Session summary (2)

   Each thread in a Java program is assigned a
    priority
   The default priority of a thread that is created
    is 5
   The methods Thread.suspend(),
    Thread.resume() and Thread.stop() have
    been deprecated since Java2
   The threads providing service to other
    threads are referred to as daemon threads
                            eACCP 2002/Sem 1/ JPL/
                           Session 6/ 26 of 26

More Related Content

PPTX
Internet Programming with Java
PPTX
Multi threading
PPT
Basic of Multithreading in JAva
PPSX
Multithreading in-java
PPTX
Multithreading in java
PPT
PPTX
L22 multi-threading-introduction
PPTX
Multi threading
Internet Programming with Java
Multi threading
Basic of Multithreading in JAva
Multithreading in-java
Multithreading in java
L22 multi-threading-introduction
Multi threading

What's hot (19)

PPTX
Multithreading in java
PPTX
Multi-threaded Programming in JAVA
PPTX
Advanced Introduction to Java Multi-Threading - Full (chok)
PPTX
Concurrency in java
PPT
Java And Multithreading
PPT
java threads
PDF
Tools for analysis and evaluation of CPU Performance
PPT
Java Multithreading
PPT
Chap2 2 1
PPT
Chapter 02
PDF
Java threads
PPT
Java Threads and Concurrency
PPT
Developing Multithreaded Applications
PPT
Thread model in java
PPTX
advanced java ppt
PDF
Java threading
PPTX
Threading concepts
PDF
Programming with Threads in Java
PPTX
Java Thread & Multithreading
Multithreading in java
Multi-threaded Programming in JAVA
Advanced Introduction to Java Multi-Threading - Full (chok)
Concurrency in java
Java And Multithreading
java threads
Tools for analysis and evaluation of CPU Performance
Java Multithreading
Chap2 2 1
Chapter 02
Java threads
Java Threads and Concurrency
Developing Multithreaded Applications
Thread model in java
advanced java ppt
Java threading
Threading concepts
Programming with Threads in Java
Java Thread & Multithreading
Ad

Viewers also liked (16)

PPTX
Windows file system
PPTX
Disaster Mangement process with Uttarakhand Case Study
PDF
Operating Systems 1 (10/12) - Scheduling
PPT
Window scheduling algorithm
PPT
Community Disaster Preparedness
PPTX
Windows process scheduling presentation
PPTX
Fault tolerance in distributed systems
PPT
Principles of Emergency Management slides
PPTX
Windows process-scheduling
PPT
The Windows Scheduler
PPTX
Disaster preparedness
PPTX
Disaster management
PPTX
Natural disaster powerpoint
PPTX
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
PPTX
Natural disasters
PPT
Disaster management ppt
Windows file system
Disaster Mangement process with Uttarakhand Case Study
Operating Systems 1 (10/12) - Scheduling
Window scheduling algorithm
Community Disaster Preparedness
Windows process scheduling presentation
Fault tolerance in distributed systems
Principles of Emergency Management slides
Windows process-scheduling
The Windows Scheduler
Disaster preparedness
Disaster management
Natural disaster powerpoint
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
Natural disasters
Disaster management ppt
Ad

Similar to Chapter6 threads (20)

PPT
ThreadProperties
PDF
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
PPT
Java multi threading
PDF
javathreads
PPTX
Java class 6
PPT
Threadlifecycle.36
PPTX
OOPS object oriented programming UNIT-4.pptx
PPTX
MULTI THREADING IN JAVA
PDF
Unit-3 MULTITHREADING-2.pdf
PPTX
Multithreading in java
PPTX
Multithreading
PPTX
multithreading,thread and processinjava-210302183809.pptx
PPTX
unit3multithreadingppt-copy-180122162204.pptx
PPTX
unit3 Exception Handling multithreadingppt.pptx
PPTX
econtent thread in java.pptx
PDF
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
PDF
Java Threads: Lightweight Processes
PPTX
Multithreading.pptx
PPTX
Object-Oriented-Prog_MultiThreading.pptx
PPTX
Multithreading programming in java
ThreadProperties
JAVA 3.2.pdfhdfkjhdfvbjdbjfhjdfhdjhfjdfdjfhdjhjd
Java multi threading
javathreads
Java class 6
Threadlifecycle.36
OOPS object oriented programming UNIT-4.pptx
MULTI THREADING IN JAVA
Unit-3 MULTITHREADING-2.pdf
Multithreading in java
Multithreading
multithreading,thread and processinjava-210302183809.pptx
unit3multithreadingppt-copy-180122162204.pptx
unit3 Exception Handling multithreadingppt.pptx
econtent thread in java.pptx
CSE 3146 M1- MULTI THREADING USING JAVA .pdf
Java Threads: Lightweight Processes
Multithreading.pptx
Object-Oriented-Prog_MultiThreading.pptx
Multithreading programming in java

Recently uploaded (20)

PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
PDF
VCE English Exam - Section C Student Revision Booklet
PPTX
Cell Types and Its function , kingdom of life
PDF
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
master seminar digital applications in india
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
RMMM.pdf make it easy to upload and study
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Trump Administration's workforce development strategy
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
PPTX
Pharma ospi slides which help in ospi learning
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
202450812 BayCHI UCSC-SV 20250812 v17.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Tissue processing ( HISTOPATHOLOGICAL TECHNIQUE
VCE English Exam - Section C Student Revision Booklet
Cell Types and Its function , kingdom of life
GENETICS IN BIOLOGY IN SECONDARY LEVEL FORM 3
Yogi Goddess Pres Conference Studio Updates
master seminar digital applications in india
Chinmaya Tiranga quiz Grand Finale.pdf
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
RMMM.pdf make it easy to upload and study
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Trump Administration's workforce development strategy
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
OBE - B.A.(HON'S) IN INTERIOR ARCHITECTURE -Ar.MOHIUDDIN.pdf
Pharma ospi slides which help in ospi learning

Chapter6 threads

  • 2. Objectives  Compare Multitasking and Multithreading  Define a thread  Discuss Benefits of multithreading  Explain how to create threads  Describe Thread states  Discuss Thread priorities  Discuss Daemon thread eACCP 2002/Sem 1/ JPL/ Session 6/ 2 of 26
  • 3. Multitasking Vs Multithreading  Multitasking is the ability to run one or more programs concurrently  Operating system controls the way in which these programs run by scheduling them  Time between switching of programs is minute  Multithreading is the ability to execute different parts of a program called threads, simultaneously eACCP 2002/Sem 1/ JPL/ Session 6/ 3 of 26
  • 4. Thread  Smallest unit of executable code that performs a task  An application can be divided into multiple tasks and each task can be assigned to a thread  Many threads executing simultaneously is termed as Multithreading  Although it may appear that the processes are running concurrently, it is not so 1/ JPL/ eACCP 2002/Sem Session 6/ 4 of 26
  • 5. Benefits of multithreading  Multithreading requires less overhead than multitasking  In multitasking, processes run in their own different address space  Tasks involved in multithreading can share the same address space  Inter-process calling involves more overhead than inter-thread communication eACCP 2002/Sem 1/ JPL/ Session 6/ 5 of 26
  • 6. Applications of thread  Playing sound and displaying images simultaneously  Displaying multiple images on the screen  Displaying scrolling text patterns or images on the screen eACCP 2002/Sem 1/ JPL/ Session 6/ 6 of 26
  • 7. Creating threads (1)  When Java programs execute, there is always one thread running and that is the main thread  It is this thread from which child threads are created  Program is terminated when main thread stops execution  Main thread can be controlled through ‘Thread’ objects eACCP 2002/Sem 1/ JPL/ Session 6/ 7 of 26
  • 8. Creating threads (2)  Thread objects can be created in two ways:  Declare a class that is a sub-class of the class Thread defined in java.lang package  class mythread extends Thread  Declare a class that implements the Runnable interface  class mythread implements Runnable  While using applets, Thread class cannot be extended. Therefore one has to implement the Runnable interface eACCP 2002/Sem 1/ JPL/ Session 6/ 8 of 26
  • 9. Creating threads (3)  To initiate a new thread, we use the start() method Mythread t = new Mythread(); t.start();  When start() method is invoked, a new thread of control is created  It then calls the run() method eACCP 2002/Sem 1/ JPL/ Session 6/ 9 of 26
  • 10. Creating threads (4) Example 1 – Creating a thread by extending the Thread class Output eACCP 2002/Sem 1/ JPL/ Session 6/ 10 of 26
  • 11. Creating threads (5) Example2 – Creating a thread by implementing the Runnable interface Output eACCP 2002/Sem 1/ JPL/ Session 6/ 11 of 26
  • 12. Thread states (1)  Born – a newly created thread is in a born state  Ready – after a thread is created, it is in its ready state waiting for start() method to be called eACCP 2002/Sem 1/ JPL/ Session 6/ 12 of 26
  • 13. Thread states (2)  Running – thread enters the running state when it starts executing  Sleeping – execution of a thread can be halted temporarily by using sleep() method. The thread becomes ready after sleep time expires eACCP 2002/Sem 1/ JPL/ Session 6/ 13 of 26
  • 14. Thread states (3)  Waiting – thread is in waiting state if wait() method has been invoked  Blocked – when the thread waits for an Input/Output operation  Dead – after the run() method has finished or the threads stop() method is2002/Sem 1/ JPL/ eACCP called Session 6/ 14 of 26
  • 15. Different thread states New Thread (BORN) READY SLEEPING SUSPENDED RUNNING WAITING BLOCKED DEADeACCP 2002/Sem 1/ JPL/ Session 6/ 15 of 26
  • 16. Some methods of thread class (1)  isAlive() – returns true if the thread is alive  getName() – returns the name of the thread  start() – used to start a thread by calling the method run() eACCP 2002/Sem 1/ JPL/ Session 6/ 16 of 26
  • 17. Some methods of thread class (2)  resume() – to resume the execution of a suspended thread  yield() – causes the currently executing thread to temporarily pause and allow other threads to execute  setName(String name) – sets the name of the thread to the name that is passed as eACCP 2002/Sem 1/ JPL/ argument Session 6/ 17 of 26
  • 18. Some methods of thread class (3)  join() – waits for the thread to die  isDaemon() – checks if the thread is a Daemon thread  activeCount() – returns the number of active threads  sleep() – used to suspend a thread for a certain period of time eACCP 2002/Sem 1/ JPL/ Session 6/ 18 of 26
  • 19. Conditions preventing thread execution  Thread is:  Not of highest priority  Put to sleep using sleep() method  Suspended using suspend() method  Thread is waiting because wait() method was called  Explicitly yielded using yield() method  Blocked for file I/O eACCP 2002/Sem 1/ JPL/ Session 6/ 19 of 26
  • 20. Managing threads (1)  Priorities for carrying out activities changes at times  eg :Planned to visit museum in the afternoon but due to toothache, had to go to doctor  Similarly while programming, we may have to run a thread of higher importance without stopping or suspending the current running thread  Thread priorities play an important role in such a situation eACCP 2002/Sem 1/ JPL/ Session 6/ 20 of 26
  • 21. Managing threads (2)  Thread priorities in Java are constants defined in the Thread class  NORM_PRIORITY – value is  MAX_PRIORITY – value is  MIN_PRIORITY – value is  The default priority is NORM_PRIORITY  Two methods used to change priority:  setPriority() - changes the thread’s current priority  getPriority() - returns the thread’s priority eACCP 2002/Sem 1/ JPL/ Session 6/ 21 of 26
  • 22. Daemon threads (1)  Two types of threads in Java:  User threads – created by the user  Daemon threads – threads that work in the background providing service to other threads  e.g. – the garbage collector thread  When user thread exits, JVM checks to find out if any other thread is running  If the only executing threads are Daemon threads, it exits eACCP 2002/Sem 1/ JPL/ Session 6/ 22 of 26
  • 23. Daemon threads (2)  We can set a thread to be a Daemon if we do not want the main program to wait until a thread ends  Thread class has two methods to deal with Daemon threads:  public void setDaemon(boolean value) : sets a thread to be a daemon thread  public void isDaemon() : checks if the given thread is a daemon thread eACCP 2002/Sem 1/ JPL/ Session 6/ 23 of 26
  • 24. Daemon threads (3) An example Output eACCP 2002/Sem 1/ JPL/ Session 6/ 24 of 26
  • 25. Session summary (1)  When Java programs are executed, there is always one thread that is running and that is the main thread  Threads can be used in two ways:  Declare the class to be a sub-class of the Thread class  Declare a class that implements the Runnable interface eACCP 2002/Sem 1/ JPL/ Session 6/ 25 of 26
  • 26. Session summary (2)  Each thread in a Java program is assigned a priority  The default priority of a thread that is created is 5  The methods Thread.suspend(), Thread.resume() and Thread.stop() have been deprecated since Java2  The threads providing service to other threads are referred to as daemon threads eACCP 2002/Sem 1/ JPL/ Session 6/ 26 of 26