SlideShare ist ein Scribd-Unternehmen logo
1 von 16
Downloaden Sie, um offline zu lesen
Multi-threading


               OOSSE - Programming with Java
                        Lecture 11




Dec 21, 2012    OOSSE - Java Lecture 11    1
Objectives
 In this lecture, we will:
 • Introduce threads
 • Discuss the Thread class and the Runnable interface
 • Discuss interrupting threads
 • Introduce concepts of thread synchronization




Dec 21, 2012   OOSSE - Java Lecture 11        2
Introduction
 • A thread is a path of execution through a program
 • Many programs exist with just a single path of execution
 • Operating systems (OS) often allow multiple processes to
   co-exist and the OS shares processor time between them
     – The processes are isolated from each by the OS
     – They should not be able to overwrite each other’s memory
 • Languages like Java, C++ and C# allow a single
   application to have more than one thread of execution
     – a thread is the smallest unit of execution in the OS
     – Multiple threads in an application share the same process
       space; they have access to the same memory




Dec 21, 2012     OOSSE - Java Lecture 11            3
Why use threads?
 • A lot of the time a computer is doing nothing!
     – Often waiting for user input or a slow peripheral device
 • A computer can use any spare time by:
     – Multitasking – more than one process competing for the CPU
     – Mulit-threading - more than one thread competing for the CPU


 • Threads can be used to:
     – Allow the application to do something else while it is waiting
     – Start more than one task at a time rather than wait for one to
       complete before starting another
         • Start processing data before all the data has loaded
     – Maintain an active user interface
         • The interface does not die while processing takes place

Dec 21, 2012       OOSSE - Java Lecture 11                4
Threads in Java
 • There are two ways of creating threads in Java:
 • The Thread class can be subclassed and an instance of
   this class used
     – This is most appropriate when the functionality of the thread
       is largely independent
 • Any class can implement the Runnable interface
     – An instance of the Thread class is constructed using an
       instance of the Runnable class as an argument
     – This is appropriate when the thread must work in the context
       of a specific object
 • In either case the key method is run
     – The life of the thread exists through the execution of run



Dec 21, 2012      OOSSE - Java Lecture 11             5
Subclassing the Thread class
 public class MyThread extends Thread {
    private String msg;
    private int num;

     public MyThread(String m, int n)
     {
           msg = m;
           num = n;
     }

     public void run(){
           // the work of the thread takes place within the run method
           // the thread terminates when the method ends
     }
 }


Dec 21, 2012         OOSSE - Java Lecture 11                6
Implementing the Runnable Interface
 public class SimpleRun implements Runnable {
    private String msg;
    private int num;

     public SimpleRun(String m, int n)
     {
           msg = m;
           num = n;
     }

     public void run(){
           // the work of the thread takes place within the run method
           // the thread terminates when the method ends
     }
 }


Dec 21, 2012         OOSSE - Java Lecture 11                7
Starting a Thread
 • Although the thread lives through the method run it is
   started by the method start
         MyThread t1;
         t1 = new MyThread("Hello",5);
         t1.start();

         Thread t2;
         t2 = new Thread(new SimpleRun("Pete", 20));
         t2.start();
 • Any code can be placed in the run method but the method
   can be interrupted and must handle the exception
     – InterruptedException
 • A thread can sleep if it wishes – normally while waiting
     – Thread.sleep( )

Dec 21, 2012        OOSSE - Java Lecture 11            8
Sample Code for the run Method
    public void run(){
          // output msg num times
          for (int i = 0; i < num; ++i)
          {
               System.out.println(msg + " " + i) ;
               try
               {
                      Thread.sleep(100);
               }
               catch (InterruptedException e)
              {
                      System.out.println("Thread interrupted: " + e);
              }
          }
    }
Dec 21, 2012         OOSSE - Java Lecture 11                   9
Potential Problems with Threads
 • It is very easy to start multiple threads
 • If the threads are largely independent then the design is
   somewhat easier
 • However, at some stage threads normally want to share
   some data
     – All threads in an application have access to the same memory
       space
 • When a thread may lose its time slice is unpredictable in
   most cases
 • Access to shared resources by multiple threads may lead to:
     – Deadlock
     – Thread starvation
     – Race conditions

Dec 21, 2012     OOSSE - Java Lecture 11           10
Thread Synchronization
 • Thread safe applications can only be built by careful
   design and appropriate use synchronization facilities
 • The most obvious problem is when one data object is
   accessed by more than one thread
     – If an update of the data is not completed then the data may
       be in an inconsistent state if accessed by another thread
 • It is possible to use locks to prevent multiple access to
   contentious code
 • Java provides:
     – Synchronized methods
     – Synchronized blocks




Dec 21, 2012      OOSSE - Java Lecture 11           11
Synchronized Methods
 • A thread can lock an object temporarily
     – Typically until it has finished using it
     – When another object tries to access the same object it is
       blocked
 • Synchronized methods are used for object locking
     – Once a thread starts executing a synchronized method it
       completes the method before any other thread can execute
       a synchronized method on the same object
     – For example:
         public class MyData{
           public synchronized void add ( … ) { … }
           public synchronized void renove ( … ) { … }
         }


Dec 21, 2012       OOSSE - Java Lecture 11               12
Wait and Notify
 • If a synchronized cannot run to completion because it
   needs a resource then it cannot simply sleep
     – Sleeping does not release the lock
     – If the resource is provided by another synchronized thread
       on the same object the supplying thread is blocked
 • Instead of sleeping the thread can wait
     – Calling wait inside a synchronized method not only makes
       the thread wait but also allows another thread to acquire the
       lock
 • A waiting thread is blocked until another thread calls
   notifyAll or notify on the object for which the thread is
   waiting



Dec 21, 2012      OOSSE - Java Lecture 11            13
Wait and Notify
 • Consider adding to and removing from a data structure
   that can hold a limited amount of data:

         public synchronized void add( … ) throws InterruptedException
         {
           while ( dataStructureIsFull() ) wait( ) ;
           // now add data …
         }
         public synchronized void remove ( … ) {
           // assuming there is some data
           // remove data – space is now available to add
           notifyAll( ); // unblock all threads waiting on this lock
         }



Dec 21, 2012    OOSSE - Java Lecture 11               14
Synchronized Blocks
 • Synchronized methods automatically lock and unlock
   objects
 • It is possible to apply a lock to a block of code
     – The lock is based upon a specific object
 • The syntax is:
     synchronized ( someObject )
     {
         // only one thread in the block of code at a time
     }

 • It is normally better to think about thread safe code at the class
   level
     – Think about using synchronized methods in preference to
       synchronized blocks


Dec 21, 2012        OOSSE - Java Lecture 11                  15
Summary
 In this lecture we have:
 • Introduced threads
 • Discussed the Thread class and the Runnable interface
 • Discussed interrupting threads
 • Introduced concepts of thread synchronization




Dec 21, 2012   OOSSE - Java Lecture 11       16

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
JAVA ENVIRONMENT
JAVA  ENVIRONMENTJAVA  ENVIRONMENT
JAVA ENVIRONMENTjosemachoco
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in javaHitesh Kumar
 
Java Collections
Java CollectionsJava Collections
Java Collectionsparag
 
5 collection framework
5 collection framework5 collection framework
5 collection frameworkMinal Maniar
 
Collections In Java
Collections In JavaCollections In Java
Collections In JavaBinoj T E
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in JavaKurapati Vishwak
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptWojciech Dzikowski
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Edureka!
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPTPooja Jaiswal
 
Constructor in java
Constructor in javaConstructor in java
Constructor in javaHitesh Kumar
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesHitesh-Java
 
Java applets
Java appletsJava applets
Java appletsPihu Goel
 

Was ist angesagt? (20)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
JAVA ENVIRONMENT
JAVA  ENVIRONMENTJAVA  ENVIRONMENT
JAVA ENVIRONMENT
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
 
Java collection
Java collectionJava collection
Java collection
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Arrays in java
Arrays in javaArrays in java
Arrays in java
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
 
Servlets
ServletsServlets
Servlets
 
Multiple inheritance possible in Java
Multiple inheritance possible in JavaMultiple inheritance possible in Java
Multiple inheritance possible in Java
 
ES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern JavascriptES2015 / ES6: Basics of modern Javascript
ES2015 / ES6: Basics of modern Javascript
 
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
Java Threads Tutorial | Multithreading In Java Tutorial | Java Tutorial For B...
 
Spring boot
Spring bootSpring boot
Spring boot
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java thread life cycle
Java thread life cycleJava thread life cycle
Java thread life cycle
 
Applets
AppletsApplets
Applets
 
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slidesSpring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
 
Java applets
Java appletsJava applets
Java applets
 

Andere mochten auch

Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency modelsAbid Khan
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Designtheamiableapi
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Nitin Aggarwal
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook   resume) job interview - 101 dynamite answers to interview questions ...(Ebook   resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...Farahaa
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Haim Yadid
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVATech_MX
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked listsAbdullah Al-hazmy
 
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
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresHitendra Kumar
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursionAbdullah Al-hazmy
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 iimjobs and hirist
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 

Andere mochten auch (16)

Alternate concurrency models
Alternate concurrency modelsAlternate concurrency models
Alternate concurrency models
 
Developer Friendly API Design
Developer Friendly API DesignDeveloper Friendly API Design
Developer Friendly API Design
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Best Coding Practices in Java and C++
Best Coding Practices in Java and C++Best Coding Practices in Java and C++
Best Coding Practices in Java and C++
 
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
(Ebook   resume) job interview - 101 dynamite answers to interview questions ...(Ebook   resume) job interview - 101 dynamite answers to interview questions ...
(Ebook resume) job interview - 101 dynamite answers to interview questions ...
 
Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014Concurrency and Multithreading Demistified - Reversim Summit 2014
Concurrency and Multithreading Demistified - Reversim Summit 2014
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Data Structures- Part7 linked lists
Data Structures- Part7 linked listsData Structures- Part7 linked lists
Data Structures- Part7 linked lists
 
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)
 
Java Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data StructuresJava Performance, Threading and Concurrent Data Structures
Java Performance, Threading and Concurrent Data Structures
 
Data Structures- Part5 recursion
Data Structures- Part5 recursionData Structures- Part5 recursion
Data Structures- Part5 recursion
 
Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014 Top 10 Java Interview Questions and Answers 2014
Top 10 Java Interview Questions and Answers 2014
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 
Java codes
Java codesJava codes
Java codes
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 

Ähnlich wie 12 multi-threading

Multithreading
MultithreadingMultithreading
MultithreadingF K
 
Java multithreading
Java multithreadingJava multithreading
Java multithreadingMohammed625
 
Java Multithreading
Java MultithreadingJava Multithreading
Java MultithreadingRajkattamuri
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in javaKavitha713564
 
Multi-threaded Programming in JAVA
Multi-threaded Programming in JAVAMulti-threaded Programming in JAVA
Multi-threaded Programming in JAVAVikram Kalyani
 
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
 
Multithreading
MultithreadingMultithreading
Multithreadingsagsharma
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptxmadan r
 
1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdfahmadkeder8
 

Ähnlich wie 12 multi-threading (20)

Java Threads
Java ThreadsJava Threads
Java Threads
 
Java
JavaJava
Java
 
multithreading
multithreadingmultithreading
multithreading
 
Java
JavaJava
Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Java multithreading
Java multithreadingJava multithreading
Java multithreading
 
Java Multithreading
Java MultithreadingJava Multithreading
Java Multithreading
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
Multithreading in java
Multithreading in javaMultithreading in java
Multithreading in java
 
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
 
Thread&amp;multithread
Thread&amp;multithreadThread&amp;multithread
Thread&amp;multithread
 
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
 
Threads
ThreadsThreads
Threads
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Multithreading
MultithreadingMultithreading
Multithreading
 
U4 JAVA.pptx
U4 JAVA.pptxU4 JAVA.pptx
U4 JAVA.pptx
 
Java threading
Java threadingJava threading
Java threading
 
1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf1. learning programming with JavaThreads.pdf
1. learning programming with JavaThreads.pdf
 

Mehr von APU

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientationAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
9. oo languages
9. oo languages9. oo languages
9. oo languagesAPU
 
8. design patterns
8. design patterns8. design patterns
8. design patternsAPU
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagramsAPU
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagramsAPU
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagramsAPU
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using umlAPU
 
3. use cases
3. use cases3. use cases
3. use casesAPU
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_moduleAPU
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languagesAPU
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classesAPU
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patternsAPU
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagramsAPU
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using umlAPU
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to umlAPU
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_moduleAPU
 
14 file handling
14 file handling14 file handling
14 file handlingAPU
 
13 gui development
13 gui development13 gui development
13 gui developmentAPU
 

Mehr von APU (20)

01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 1. introduction to object orientation
. 1. introduction to object orientation. 1. introduction to object orientation
. 1. introduction to object orientation
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
9. oo languages
9. oo languages9. oo languages
9. oo languages
 
8. design patterns
8. design patterns8. design patterns
8. design patterns
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 
6. activity diagrams
6. activity diagrams6. activity diagrams
6. activity diagrams
 
5. state diagrams
5. state diagrams5. state diagrams
5. state diagrams
 
4. class diagrams using uml
4. class diagrams using uml4. class diagrams using uml
4. class diagrams using uml
 
3. use cases
3. use cases3. use cases
3. use cases
 
01 introduction to_module
01 introduction to_module01 introduction to_module
01 introduction to_module
 
. 9. oo languages
. 9. oo languages. 9. oo languages
. 9. oo languages
 
08 aggregation and collection classes
08  aggregation and collection classes08  aggregation and collection classes
08 aggregation and collection classes
 
. 8. design patterns
. 8. design patterns. 8. design patterns
. 8. design patterns
 
. 5. state diagrams
. 5. state diagrams. 5. state diagrams
. 5. state diagrams
 
. 4. class diagrams using uml
. 4. class diagrams using uml. 4. class diagrams using uml
. 4. class diagrams using uml
 
. 2. introduction to uml
. 2. introduction to uml. 2. introduction to uml
. 2. introduction to uml
 
. 01 introduction_to_module
. 01 introduction_to_module. 01 introduction_to_module
. 01 introduction_to_module
 
14 file handling
14 file handling14 file handling
14 file handling
 
13 gui development
13 gui development13 gui development
13 gui development
 

12 multi-threading

  • 1. Multi-threading OOSSE - Programming with Java Lecture 11 Dec 21, 2012 OOSSE - Java Lecture 11 1
  • 2. Objectives In this lecture, we will: • Introduce threads • Discuss the Thread class and the Runnable interface • Discuss interrupting threads • Introduce concepts of thread synchronization Dec 21, 2012 OOSSE - Java Lecture 11 2
  • 3. Introduction • A thread is a path of execution through a program • Many programs exist with just a single path of execution • Operating systems (OS) often allow multiple processes to co-exist and the OS shares processor time between them – The processes are isolated from each by the OS – They should not be able to overwrite each other’s memory • Languages like Java, C++ and C# allow a single application to have more than one thread of execution – a thread is the smallest unit of execution in the OS – Multiple threads in an application share the same process space; they have access to the same memory Dec 21, 2012 OOSSE - Java Lecture 11 3
  • 4. Why use threads? • A lot of the time a computer is doing nothing! – Often waiting for user input or a slow peripheral device • A computer can use any spare time by: – Multitasking – more than one process competing for the CPU – Mulit-threading - more than one thread competing for the CPU • Threads can be used to: – Allow the application to do something else while it is waiting – Start more than one task at a time rather than wait for one to complete before starting another • Start processing data before all the data has loaded – Maintain an active user interface • The interface does not die while processing takes place Dec 21, 2012 OOSSE - Java Lecture 11 4
  • 5. Threads in Java • There are two ways of creating threads in Java: • The Thread class can be subclassed and an instance of this class used – This is most appropriate when the functionality of the thread is largely independent • Any class can implement the Runnable interface – An instance of the Thread class is constructed using an instance of the Runnable class as an argument – This is appropriate when the thread must work in the context of a specific object • In either case the key method is run – The life of the thread exists through the execution of run Dec 21, 2012 OOSSE - Java Lecture 11 5
  • 6. Subclassing the Thread class public class MyThread extends Thread { private String msg; private int num; public MyThread(String m, int n) { msg = m; num = n; } public void run(){ // the work of the thread takes place within the run method // the thread terminates when the method ends } } Dec 21, 2012 OOSSE - Java Lecture 11 6
  • 7. Implementing the Runnable Interface public class SimpleRun implements Runnable { private String msg; private int num; public SimpleRun(String m, int n) { msg = m; num = n; } public void run(){ // the work of the thread takes place within the run method // the thread terminates when the method ends } } Dec 21, 2012 OOSSE - Java Lecture 11 7
  • 8. Starting a Thread • Although the thread lives through the method run it is started by the method start MyThread t1; t1 = new MyThread("Hello",5); t1.start(); Thread t2; t2 = new Thread(new SimpleRun("Pete", 20)); t2.start(); • Any code can be placed in the run method but the method can be interrupted and must handle the exception – InterruptedException • A thread can sleep if it wishes – normally while waiting – Thread.sleep( ) Dec 21, 2012 OOSSE - Java Lecture 11 8
  • 9. Sample Code for the run Method public void run(){ // output msg num times for (int i = 0; i < num; ++i) { System.out.println(msg + " " + i) ; try { Thread.sleep(100); } catch (InterruptedException e) { System.out.println("Thread interrupted: " + e); } } } Dec 21, 2012 OOSSE - Java Lecture 11 9
  • 10. Potential Problems with Threads • It is very easy to start multiple threads • If the threads are largely independent then the design is somewhat easier • However, at some stage threads normally want to share some data – All threads in an application have access to the same memory space • When a thread may lose its time slice is unpredictable in most cases • Access to shared resources by multiple threads may lead to: – Deadlock – Thread starvation – Race conditions Dec 21, 2012 OOSSE - Java Lecture 11 10
  • 11. Thread Synchronization • Thread safe applications can only be built by careful design and appropriate use synchronization facilities • The most obvious problem is when one data object is accessed by more than one thread – If an update of the data is not completed then the data may be in an inconsistent state if accessed by another thread • It is possible to use locks to prevent multiple access to contentious code • Java provides: – Synchronized methods – Synchronized blocks Dec 21, 2012 OOSSE - Java Lecture 11 11
  • 12. Synchronized Methods • A thread can lock an object temporarily – Typically until it has finished using it – When another object tries to access the same object it is blocked • Synchronized methods are used for object locking – Once a thread starts executing a synchronized method it completes the method before any other thread can execute a synchronized method on the same object – For example: public class MyData{ public synchronized void add ( … ) { … } public synchronized void renove ( … ) { … } } Dec 21, 2012 OOSSE - Java Lecture 11 12
  • 13. Wait and Notify • If a synchronized cannot run to completion because it needs a resource then it cannot simply sleep – Sleeping does not release the lock – If the resource is provided by another synchronized thread on the same object the supplying thread is blocked • Instead of sleeping the thread can wait – Calling wait inside a synchronized method not only makes the thread wait but also allows another thread to acquire the lock • A waiting thread is blocked until another thread calls notifyAll or notify on the object for which the thread is waiting Dec 21, 2012 OOSSE - Java Lecture 11 13
  • 14. Wait and Notify • Consider adding to and removing from a data structure that can hold a limited amount of data: public synchronized void add( … ) throws InterruptedException { while ( dataStructureIsFull() ) wait( ) ; // now add data … } public synchronized void remove ( … ) { // assuming there is some data // remove data – space is now available to add notifyAll( ); // unblock all threads waiting on this lock } Dec 21, 2012 OOSSE - Java Lecture 11 14
  • 15. Synchronized Blocks • Synchronized methods automatically lock and unlock objects • It is possible to apply a lock to a block of code – The lock is based upon a specific object • The syntax is: synchronized ( someObject ) { // only one thread in the block of code at a time } • It is normally better to think about thread safe code at the class level – Think about using synchronized methods in preference to synchronized blocks Dec 21, 2012 OOSSE - Java Lecture 11 15
  • 16. Summary In this lecture we have: • Introduced threads • Discussed the Thread class and the Runnable interface • Discussed interrupting threads • Introduced concepts of thread synchronization Dec 21, 2012 OOSSE - Java Lecture 11 16

Hinweis der Redaktion

  1. Part of this lecture will be reserved for working through solutions to selected exercises from last week. Notes relating to this do not appear in the slides.