SlideShare una empresa de Scribd logo
1 de 27
Java Threads




               1
Multitasking and Multithreading
• Multitasking:
  – refers to a computer's ability to perform multiple jobs
    concurrently
  – more than one program are running concurrently, e.g.,
    UNIX
• Multithreading:
  – A thread is a single sequence of execution within a
    program
  – refers to multiple threads of control within a single
    program
  – each program can run multiple threads of control within
    it, e.g., Web Browser
                                                              2
Concurrency vs. Parallelism
CPU             CPU1      CPU2




                                 3
Threads and Processes
                        CPU



                                main


                                run

Process 1   Process 2         Process 3   Process 4



                                 GC




                                                      4
What are Threads Good For?

• To maintain responsiveness of an application
  during a long running task
• To enable cancellation of separable tasks
• Some problems are intrinsically parallel
• To monitor status of some resource (e.g., DB)
• Some APIs and systems demand it (e.g., Swing)



                                                  5
Application Thread

•   When we execute an application:
    1. The JVM creates a Thread object whose task
       is defined by the main() method
    2. The JVM starts the thread
    3. The thread executes the statements of the
       program one by one
    4. After executing all the statements, the method
       returns and the thread dies
                                                        6
Multiple Threads in an Application

• Each thread has its private run-time stack
• If two threads execute the same method, each will
  have its own copy of the local variables the
  methods uses
• However, all threads see the same dynamic
  memory, i.e., heap (are there variables on the
  heap?)
• Two different threads can act on the same object
  and same static fields concurrently
                                                      7
Creating Threads

•   There are two ways to create our own
    Thread object
    1. Subclassing the Thread class and instantiating
       a new object of that class
    2. Implementing the Runnable interface
•   In both cases the run() method should be
    implemented
                                                        8
Extending Thread
public class ThreadExample extends Thread {
    public void run () {
        for (int i = 1; i <= 100; i++) {
            System.out.println(“---”);
        }
    }
}




                                              9
Thread Methods

void start()
  – Creates a new thread and makes it runnable
  – This method can be called only once
void run()
  – The new thread begins its life inside this method
void stop() (deprecated)
  – The thread is being terminated

                                                        10
Thread Methods
void yield()
  – Causes the currently executing thread object to
    temporarily pause and allow other threads to
    execute
  – Allow only threads of the same priority to run
void sleep(int m) or sleep(int m, int n)  
  – The thread sleeps for m milliseconds, plus n
    nanoseconds

                                                      11
Implementing Runnable
public class RunnableExample implements Runnable {
    public void run () {
        for (int i = 1; i <= 100; i++) {
                   System.out.println (“***”);
        }
    }
}




                                                     12
A Runnable Object

• When running the Runnable object, a
 Thread object is created from the Runnable
 object
• The Thread object’s run() method calls the
 Runnable object’s run() method
• Allows threads to run inside any object,
 regardless of inheritance     Example – an applet
                               that is also a thread 13
Starting the Threads
public class ThreadsStartExample {
      public static void main (String argv[]) {
          new ThreadExample ().start ();
          new Thread(new RunnableExample ()).start ();
      }
}




           What will we see when running
             ThreadsStartExample?


                                                         14
15
Scheduling Threads
               start()
                                                Ready queue

    Newly created
    threads


 Currently executed
 thread
                   I/O operation completes

                     •Waiting for I/O operation to be   completed
What happens when    •Waiting to be notified
a program with a     •Sleeping
ServerSocket calls   •Waiting to enter a synchronized   section
accept()?                                                         16
Thread State Diagram

                       Alive


                               Running
new ThreadExample();           while (…) { … }

New Thread                     Runnable                     Dead Thread
             thread.start();
                                                       run() method returns


                               Blocked
                                             Object.wait()
                                             Thread.sleep()
                                             blocking IO call
                                             waiting on a monitor         17
Example
public class PrintThread1 extends Thread {
    String name;
    public PrintThread1(String name) {
        this.name = name;
    }
    public void run() {
        for (int i=1; i<100 ; i++) {
            try {
                sleep((long)(Math.random() * 100));
            } catch (InterruptedException ie) { }
            System.out.print(name);
        }
}
                                                      18
Example (cont)
    public static void main(String args[]) {
         PrintThread1 a = new PrintThread1("*");
         PrintThread1 b = new PrintThread1("-");


         a.start();
         b.start();
    }
}




                                                   19
20
Scheduling

• Thread scheduling is the mechanism used
 to determine how runnable threads are
 allocated CPU time
• A thread-scheduling mechanism is either
 preemptive or nonpreemptive



                                            21
Preemptive Scheduling

• Preemptive scheduling – the thread scheduler
  preempts (pauses) a running thread to allow
  different threads to execute
• Nonpreemptive scheduling – the scheduler never
  interrupts a running thread
• The nonpreemptive scheduler relies on the running
  thread to yield control of the CPU so that other
  threads may execute
                                                     22
Thread Priority

• Every thread has a priority
• When a thread is created, it inherits the
 priority of the thread that created it
• The priority values range from 1 to 10,
 in increasing priority


                                              23
Thread Priority (cont.)

• The priority can be adjusted subsequently using
  the setPriority() method
• The priority of a thread may be obtained using
  getPriority()

• Priority constants are defined:
  – MIN_PRIORITY=1
  – MAX_PRIORITY=10             The main thread is
                                created with priority
  – NORM_PRIORITY=5
                                NORM_PRIORITY
                                                        24
Daemon Threads
• Daemon threads are “background” threads, that
  provide services to other threads, e.g., the garbage
  collection thread
• The Java VM will not exit if non-Daemon threads
  are executing
• The Java VM will exit if only Daemon threads are
  executing
• Daemon threads die when the Java VM exits
• Q: Is the main thread a daemon thread?
                                                     25
Thread and the Garbage Collector

• Can a Thread object be collected by the
 garbage collector while running?
  – If not, why?
  – If yes, what happens to the execution thread?

• When can a Thread object be collected?



                                                    26
ThreadGroup

• The ThreadGroup class is used to create
 groups of similar threads. Why is this
 needed?

   “Thread groups are best viewed as an
   unsuccessful experiment, and you may simply
   ignore their existence.”
               Joshua Bloch, software architect at Sun

                                                         27

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

Exception Handling in JAVA
Exception Handling in JAVAException Handling in JAVA
Exception Handling in JAVA
 
Files in java
Files in javaFiles in java
Files in java
 
Java constructors
Java constructorsJava constructors
Java constructors
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Method overloading
Method overloadingMethod overloading
Method overloading
 
Io streams
Io streamsIo streams
Io streams
 
MULTI THREADING IN JAVA
MULTI THREADING IN JAVAMULTI THREADING IN JAVA
MULTI THREADING IN JAVA
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
java interface and packages
java interface and packagesjava interface and packages
java interface and packages
 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Basic of Multithreading in JAva
Basic of Multithreading in JAvaBasic of Multithreading in JAva
Basic of Multithreading in JAva
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Java: GUI
Java: GUIJava: GUI
Java: GUI
 
Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)Basic Concepts of OOPs (Object Oriented Programming in Java)
Basic Concepts of OOPs (Object Oriented Programming in Java)
 

Destacado

Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in JavaAllan Huang
 
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
 
Multithreading
MultithreadingMultithreading
MultithreadingA B Shinde
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaRaghu nath
 

Destacado (7)

Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency 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)
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Multithreading Concepts
Multithreading ConceptsMultithreading Concepts
Multithreading Concepts
 
Chap2 2 1
Chap2 2 1Chap2 2 1
Chap2 2 1
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 

Similar a Java multi threading

Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreadingssusere538f7
 
Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024Java-Threads And Concurrency Presentation. 2024
Java-Threads And Concurrency Presentation. 2024nehakumari0xf
 
Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024Java Threads And Concurrency Presentation. 2024
Java Threads And Concurrency Presentation. 2024kashyapneha2809
 
Java class 6
Java class 6Java class 6
Java class 6Edureka!
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34myrajendra
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreadingKuntal Bhowmick
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadKartik Dube
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.pptsarthakgithub
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadPropertiesmyrajendra
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in JavaJayant Dalvi
 
1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdfahmadkeder8
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxArulmozhivarman8
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptxramyan49
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 

Similar a Java multi threading (20)

Threads
ThreadsThreads
Threads
 
Threads in java, Multitasking and Multithreading
Threads in java, Multitasking and MultithreadingThreads in java, Multitasking and Multithreading
Threads in java, Multitasking and Multithreading
 
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
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Java class 6
Java class 6Java class 6
Java class 6
 
Runnable interface.34
Runnable interface.34Runnable interface.34
Runnable interface.34
 
Threads
ThreadsThreads
Threads
 
Class notes(week 9) on multithreading
Class notes(week 9) on multithreadingClass notes(week 9) on multithreading
Class notes(week 9) on multithreading
 
Multithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of threadMultithreading Introduction and Lifecyle of thread
Multithreading Introduction and Lifecyle of thread
 
javathreads
javathreadsjavathreads
javathreads
 
BCA MultiThreading.ppt
BCA MultiThreading.pptBCA MultiThreading.ppt
BCA MultiThreading.ppt
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
ThreadProperties
ThreadPropertiesThreadProperties
ThreadProperties
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf
 
Multithreading
MultithreadingMultithreading
Multithreading
 
OOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptxOOPS object oriented programming UNIT-4.pptx
OOPS object oriented programming UNIT-4.pptx
 
econtent thread in java.pptx
econtent thread in java.pptxecontent thread in java.pptx
econtent thread in java.pptx
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 

Más de Raja Sekhar

Exception handling
Exception handlingException handling
Exception handlingRaja Sekhar
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming NeedsRaja Sekhar
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in javaRaja Sekhar
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsRaja Sekhar
 

Más de Raja Sekhar (8)

Exception handling
Exception handlingException handling
Exception handling
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Java packages
Java packagesJava packages
Java packages
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
java Basic Programming Needs
java Basic Programming Needsjava Basic Programming Needs
java Basic Programming Needs
 
Class object method constructors in java
Class object method constructors in javaClass object method constructors in java
Class object method constructors in java
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Java Starting
Java StartingJava Starting
Java Starting
 

Último

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 

Último (20)

SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 

Java multi threading

  • 2. Multitasking and Multithreading • Multitasking: – refers to a computer's ability to perform multiple jobs concurrently – more than one program are running concurrently, e.g., UNIX • Multithreading: – A thread is a single sequence of execution within a program – refers to multiple threads of control within a single program – each program can run multiple threads of control within it, e.g., Web Browser 2
  • 4. Threads and Processes CPU main run Process 1 Process 2 Process 3 Process 4 GC 4
  • 5. What are Threads Good For? • To maintain responsiveness of an application during a long running task • To enable cancellation of separable tasks • Some problems are intrinsically parallel • To monitor status of some resource (e.g., DB) • Some APIs and systems demand it (e.g., Swing) 5
  • 6. Application Thread • When we execute an application: 1. The JVM creates a Thread object whose task is defined by the main() method 2. The JVM starts the thread 3. The thread executes the statements of the program one by one 4. After executing all the statements, the method returns and the thread dies 6
  • 7. Multiple Threads in an Application • Each thread has its private run-time stack • If two threads execute the same method, each will have its own copy of the local variables the methods uses • However, all threads see the same dynamic memory, i.e., heap (are there variables on the heap?) • Two different threads can act on the same object and same static fields concurrently 7
  • 8. Creating Threads • There are two ways to create our own Thread object 1. Subclassing the Thread class and instantiating a new object of that class 2. Implementing the Runnable interface • In both cases the run() method should be implemented 8
  • 9. Extending Thread public class ThreadExample extends Thread { public void run () { for (int i = 1; i <= 100; i++) { System.out.println(“---”); } } } 9
  • 10. Thread Methods void start() – Creates a new thread and makes it runnable – This method can be called only once void run() – The new thread begins its life inside this method void stop() (deprecated) – The thread is being terminated 10
  • 11. Thread Methods void yield() – Causes the currently executing thread object to temporarily pause and allow other threads to execute – Allow only threads of the same priority to run void sleep(int m) or sleep(int m, int n)   – The thread sleeps for m milliseconds, plus n nanoseconds 11
  • 12. Implementing Runnable public class RunnableExample implements Runnable { public void run () { for (int i = 1; i <= 100; i++) { System.out.println (“***”); } } } 12
  • 13. A Runnable Object • When running the Runnable object, a Thread object is created from the Runnable object • The Thread object’s run() method calls the Runnable object’s run() method • Allows threads to run inside any object, regardless of inheritance Example – an applet that is also a thread 13
  • 14. Starting the Threads public class ThreadsStartExample { public static void main (String argv[]) { new ThreadExample ().start (); new Thread(new RunnableExample ()).start (); } } What will we see when running ThreadsStartExample? 14
  • 15. 15
  • 16. Scheduling Threads start() Ready queue Newly created threads Currently executed thread I/O operation completes •Waiting for I/O operation to be completed What happens when •Waiting to be notified a program with a •Sleeping ServerSocket calls •Waiting to enter a synchronized section accept()? 16
  • 17. Thread State Diagram Alive Running new ThreadExample(); while (…) { … } New Thread Runnable Dead Thread thread.start(); run() method returns Blocked Object.wait() Thread.sleep() blocking IO call waiting on a monitor 17
  • 18. Example public class PrintThread1 extends Thread { String name; public PrintThread1(String name) { this.name = name; } public void run() { for (int i=1; i<100 ; i++) { try { sleep((long)(Math.random() * 100)); } catch (InterruptedException ie) { } System.out.print(name); } } 18
  • 19. Example (cont) public static void main(String args[]) { PrintThread1 a = new PrintThread1("*"); PrintThread1 b = new PrintThread1("-"); a.start(); b.start(); } } 19
  • 20. 20
  • 21. Scheduling • Thread scheduling is the mechanism used to determine how runnable threads are allocated CPU time • A thread-scheduling mechanism is either preemptive or nonpreemptive 21
  • 22. Preemptive Scheduling • Preemptive scheduling – the thread scheduler preempts (pauses) a running thread to allow different threads to execute • Nonpreemptive scheduling – the scheduler never interrupts a running thread • The nonpreemptive scheduler relies on the running thread to yield control of the CPU so that other threads may execute 22
  • 23. Thread Priority • Every thread has a priority • When a thread is created, it inherits the priority of the thread that created it • The priority values range from 1 to 10, in increasing priority 23
  • 24. Thread Priority (cont.) • The priority can be adjusted subsequently using the setPriority() method • The priority of a thread may be obtained using getPriority() • Priority constants are defined: – MIN_PRIORITY=1 – MAX_PRIORITY=10 The main thread is created with priority – NORM_PRIORITY=5 NORM_PRIORITY 24
  • 25. Daemon Threads • Daemon threads are “background” threads, that provide services to other threads, e.g., the garbage collection thread • The Java VM will not exit if non-Daemon threads are executing • The Java VM will exit if only Daemon threads are executing • Daemon threads die when the Java VM exits • Q: Is the main thread a daemon thread? 25
  • 26. Thread and the Garbage Collector • Can a Thread object be collected by the garbage collector while running? – If not, why? – If yes, what happens to the execution thread? • When can a Thread object be collected? 26
  • 27. ThreadGroup • The ThreadGroup class is used to create groups of similar threads. Why is this needed? “Thread groups are best viewed as an unsuccessful experiment, and you may simply ignore their existence.” Joshua Bloch, software architect at Sun 27