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

What's hot

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
junnubabu
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
Vikram Kalyani
 
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
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
Abhra Basak
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
Shraddha
 
java threads
java threadsjava threads
java threads
Waheed Warraich
 
Tools for analysis and evaluation of CPU Performance
Tools for analysis and evaluation of CPU PerformanceTools for analysis and evaluation of CPU Performance
Tools for analysis and evaluation of CPU Performance
Mourad Bouache
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
Rajkattamuri
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
Hemo Chella
 
Chapter 02
Chapter 02Chapter 02
Chapter 02
Geonyzl Alviola
 
Java threads
Java threadsJava threads
Java threads
Prabhakaran V M
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
Sunil OS
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
Bharat17485
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
AmbigaMurugesan
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
PreetiDixit22
 
Java threading
Java threadingJava threading
Java threading
Chinh Ngo Nguyen
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
Raheemaparveen
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
koji lin
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
jehan1987
 

What's hot (19)

Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVA
 
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)
 
Concurrency in java
Concurrency in javaConcurrency in java
Concurrency in java
 
Java And Multithreading
Java And MultithreadingJava And Multithreading
Java And Multithreading
 
java threads
java threadsjava threads
java threads
 
Tools for analysis and evaluation of CPU Performance
Tools for analysis and evaluation of CPU PerformanceTools for analysis and evaluation of CPU Performance
Tools for analysis and evaluation of CPU Performance
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Chapter 02
Chapter 02Chapter 02
Chapter 02
 
Java threads
Java threadsJava threads
Java threads
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Developing Multithreaded Applications
Developing Multithreaded ApplicationsDeveloping Multithreaded Applications
Developing Multithreaded Applications
 
Thread model in java
Thread model in javaThread model in java
Thread model in java
 
advanced java ppt
advanced java pptadvanced java ppt
advanced java ppt
 
Java threading
Java threadingJava threading
Java threading
 
Threading concepts
Threading conceptsThreading concepts
Threading concepts
 
Programming with Threads in Java
Programming with Threads in JavaProgramming with Threads in Java
Programming with Threads in Java
 
Java Thread & Multithreading
Java Thread & MultithreadingJava Thread & Multithreading
Java Thread & Multithreading
 

Viewers also liked

Windows file system
Windows file systemWindows file system
Windows file system
sumitjain2013
 
Disaster Mangement process with Uttarakhand Case Study
Disaster Mangement process with Uttarakhand Case StudyDisaster Mangement process with Uttarakhand Case Study
Disaster Mangement process with Uttarakhand Case Study
Avinash Chavan
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - Scheduling
Peter Tröger
 
Window scheduling algorithm
Window scheduling algorithmWindow scheduling algorithm
Window scheduling algorithm
Binal Parekh
 
Community Disaster Preparedness
Community Disaster PreparednessCommunity Disaster Preparedness
Community Disaster Preparedness
Central Texas VOAD
 
Windows process scheduling presentation
Windows process scheduling presentationWindows process scheduling presentation
Windows process scheduling presentation
Talha Shaikh
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systems
sumitjain2013
 
Principles of Emergency Management slides
Principles of Emergency Management slidesPrinciples of Emergency Management slides
Principles of Emergency Management slides
João Canas
 
Windows process-scheduling
Windows process-schedulingWindows process-scheduling
Windows process-scheduling
Talha Shaikh
 
The Windows Scheduler
The Windows SchedulerThe Windows Scheduler
The Windows Scheduler
Peter Shirley-Quirk
 
Disaster preparedness
Disaster preparednessDisaster preparedness
Disaster preparedness
Lomer Oanilacam
 
Disaster management
Disaster managementDisaster management
Disaster management
vishwajeet bajwan
 
Natural disaster powerpoint
Natural disaster powerpointNatural disaster powerpoint
Natural disaster powerpoint
Nbort
 
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLEEDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
Sabeel Irshad
 
Natural disasters
Natural disasters Natural disasters
Natural disasters
avy123
 
Disaster management ppt
Disaster management pptDisaster management ppt
Disaster management ppt
Aniket Pingale
 

Viewers also liked (16)

Windows file system
Windows file systemWindows file system
Windows file system
 
Disaster Mangement process with Uttarakhand Case Study
Disaster Mangement process with Uttarakhand Case StudyDisaster Mangement process with Uttarakhand Case Study
Disaster Mangement process with Uttarakhand Case Study
 
Operating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - SchedulingOperating Systems 1 (10/12) - Scheduling
Operating Systems 1 (10/12) - Scheduling
 
Window scheduling algorithm
Window scheduling algorithmWindow scheduling algorithm
Window scheduling algorithm
 
Community Disaster Preparedness
Community Disaster PreparednessCommunity Disaster Preparedness
Community Disaster Preparedness
 
Windows process scheduling presentation
Windows process scheduling presentationWindows process scheduling presentation
Windows process scheduling presentation
 
Fault tolerance in distributed systems
Fault tolerance in distributed systemsFault tolerance in distributed systems
Fault tolerance in distributed systems
 
Principles of Emergency Management slides
Principles of Emergency Management slidesPrinciples of Emergency Management slides
Principles of Emergency Management slides
 
Windows process-scheduling
Windows process-schedulingWindows process-scheduling
Windows process-scheduling
 
The Windows Scheduler
The Windows SchedulerThe Windows Scheduler
The Windows Scheduler
 
Disaster preparedness
Disaster preparednessDisaster preparedness
Disaster preparedness
 
Disaster management
Disaster managementDisaster management
Disaster management
 
Natural disaster powerpoint
Natural disaster powerpointNatural disaster powerpoint
Natural disaster powerpoint
 
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLEEDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
EDLC-EMBEDDED PRODUCT DEVELOPMENT LIFE CYCLE
 
Natural disasters
Natural disasters Natural disasters
Natural disasters
 
Disaster management ppt
Disaster management pptDisaster management ppt
Disaster management ppt
 

Similar to Chapter6 threads

Java
JavaJava
Thread&multithread
Thread&multithreadThread&multithread
Thread&multithread
PhD Research Scholar
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
Kuntal Bhowmick
 
Slot02 concurrency1
Slot02 concurrency1Slot02 concurrency1
Slot02 concurrency1
Viên Mai
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Raghu nath
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
kashyapneha2809
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
nehakumari0xf
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
ssuserec53e73
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
HarshaDokula
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
Riccardo Cardin
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
Shipra Swati
 
Project Loom
Project LoomProject Loom
Project Loom
Ivelin Yanev
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
arnavytstudio2814
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
Rajesh Ananda Kumar
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
BalasundaramSr
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
Rakesh Madugula
 
Java Threads
Java ThreadsJava Threads
Java Threads
Hamid Ghorbani
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
ajmalhamidi1380
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
Monika Mishra
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
Himanshu Rajput
 

Similar to Chapter6 threads (20)

Java
JavaJava
Java
 
Thread&multithread
Thread&multithreadThread&multithread
Thread&multithread
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Slot02 concurrency1
Slot02 concurrency1Slot02 concurrency1
Slot02 concurrency1
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Project Loom
Project LoomProject Loom
Project Loom
 
Multithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming languageMultithreading in Java Object Oriented Programming language
Multithreading in Java Object Oriented Programming language
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
Threading.pptx
Threading.pptxThreading.pptx
Threading.pptx
 
Md09 multithreading
Md09 multithreadingMd09 multithreading
Md09 multithreading
 
Java Threads
Java ThreadsJava Threads
Java Threads
 
Slide 7 Thread-1.pptx
Slide 7 Thread-1.pptxSlide 7 Thread-1.pptx
Slide 7 Thread-1.pptx
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Threadnotes
ThreadnotesThreadnotes
Threadnotes
 

Recently uploaded

Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
TechSoup
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
imrankhan141184
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
Colégio Santa Teresinha
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Fajar Baskoro
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
BoudhayanBhattachari
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
dot55audits
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
Dr. Mulla Adam Ali
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
Priyankaranawat4
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
ssuser13ffe4
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
History of Stoke Newington
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Leena Ghag-Sakpal
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 

Recently uploaded (20)

Leveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit InnovationLeveraging Generative AI to Drive Nonprofit Innovation
Leveraging Generative AI to Drive Nonprofit Innovation
 
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
Traditional Musical Instruments of Arunachal Pradesh and Uttar Pradesh - RAYH...
 
MARY JANE WILSON, A “BOA MÃE” .
MARY JANE WILSON, A “BOA MÃE”           .MARY JANE WILSON, A “BOA MÃE”           .
MARY JANE WILSON, A “BOA MÃE” .
 
Pengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptxPengantar Penggunaan Flutter - Dart programming language1.pptx
Pengantar Penggunaan Flutter - Dart programming language1.pptx
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
B. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdfB. Ed Syllabus for babasaheb ambedkar education university.pdf
B. Ed Syllabus for babasaheb ambedkar education university.pdf
 
ZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptxZK on Polkadot zero knowledge proofs - sub0.pptx
ZK on Polkadot zero knowledge proofs - sub0.pptx
 
Hindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdfHindi varnamala | hindi alphabet PPT.pdf
Hindi varnamala | hindi alphabet PPT.pdf
 
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdfANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
ANATOMY AND BIOMECHANICS OF HIP JOINT.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
math operations ued in python and all used
math operations ued in python and all usedmath operations ued in python and all used
math operations ued in python and all used
 
The History of Stoke Newington Street Names
The History of Stoke Newington Street NamesThe History of Stoke Newington Street Names
The History of Stoke Newington Street Names
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
Bed Making ( Introduction, Purpose, Types, Articles, Scientific principles, N...
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 

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