SlideShare ist ein Scribd-Unternehmen logo
1 von 24
Java Programming Language
Objectives


                In this session, you will learn to:
                   Define a thread
                   Create separate threads in a Java technology program,
                   controlling the code and data that are used by that thread
                   Control the execution of a thread and write platform
                   independent code with threads
                   Describe the difficulties that might arise when multiple threads
                   share data
                   Use wait and notify to communicate between threads
                   Use synchronized to protect data from corruption




     Ver. 1.0                        Session 13                             Slide 1 of 24
Java Programming Language
Threads


               Threads are a virtual CPU.
               The three parts of the thread are:
                  CPU
                  Code
                  Data

                                                    A thread or
                                                    execution context




    Ver. 1.0                      Session 13                            Slide 2 of 24
Java Programming Language
Creating the Thread


                • Extend the class from Thread Class. For example:
                   public class HelloRunner extends Thread
                      {
                        //code
                       }
                • Implement the Runnable interface. For example:
                   class HelloRunner implements Runnable
                       {
                        //code
                       }




     Ver. 1.0                      Session 13                      Slide 3 of 24
Java Programming Language
Creating the Thread (Contd.)


                Multithreaded programming has following characteristics:
                   Multiple threads are from one Runnable instance.
                   Threads share the same data and code. For example:
                    Thread t1 = new Thread(r);
                    Thread t2 = new Thread(r);




     Ver. 1.0                      Session 13                           Slide 4 of 24
Java Programming Language
Starting the Thread


                • Use the start() method
                • Place the thread in a runnable state




     Ver. 1.0                        Session 13          Slide 5 of 24
Java Programming Language
Thread Scheduling


                 Fundamental Thread State Diagram:




                                Blocked                            Dead
          New
                    Unblocked                  Event Blocked


       start()                                                 run() Completes
                     Runnable    Scheduler Running




     Ver. 1.0                     Session 13                        Slide 6 of 24
Java Programming Language
Thread Scheduling (Contd.)


                Thread Scheduling Example:
                  public class Runner implements Runnable
                   {public void run()
                    {while (true){
                      // Do lots of interesting stuff
                      // Give other threads a chance
                      try{                                  One of Thread
                          Thread.sleep(10);                 Scheduling Method

                      }catch (InterruptedException e)
                      {
                      // This thread’s sleep was interrupted by another
                      thread
                      }}}}
     Ver. 1.0                     Session 13                         Slide 7 of 24
Java Programming Language
Terminating a Thread


                • The thread comes to the end of its run() method.
                • The thread throws an Exception or Error that is not caught.
                • Another thread calls one of the deprecated stop()
                  methods.




     Ver. 1.0                         Session 13                       Slide 8 of 24
Java Programming Language
Basic Control of Threads


                Test Threads:
                   isAlive()
                Access Thread Priority:
                   getPriority()
                   setPriority()
                Put Threads on Hold:
                   Thread.sleep() // static method
                   join()
                   Thread.yield() // static method




     Ver. 1.0                      Session 13        Slide 9 of 24
Java Programming Language
Basic Control of Threads (Contd.)


                • Use of join() method:
                   public static void main(String[] args) {
                   Thread t = new Thread(new Runner());
                   t.start();
                  // Do stuff in parallel with the other thread for a while
                  // Wait here for the other thread to finish
                  try {
                          t.join();
                      }
                  catch (InterruptedException e)
                      {
                  // the other thread came back early
                        }
                  // Now continue in this thread
                  }
     Ver. 1.0                           Session 13                            Slide 10 of 24
Java Programming Language
The Object Lock Flag


                Every object has a flag that is a type of lock flag.
                The synchronized enables interaction with the lock flag.

                Object this                Thread before synchronized(this)

                                            public void push (char c)
                                             {
                                              synchronized(this) {
                                              data[idx] = c;
                                              idx++;
                                             }
                                           }




     Ver. 1.0                      Session 13                        Slide 11 of 24
Java Programming Language
The Object Lock Flag (Contd.)




                Object this           Thread after synchronized(this)

                                      public void push (char c)
                                       {synchronized(this)
                                      {
                                       data[idx] = c;
                                       idx++;
                                       }
                                      }




     Ver. 1.0                   Session 13                      Slide 12 of 24
Java Programming Language
The Object Lock Flag (Contd.)




                Object this
                lock flag missing               Another thread, trying to execute
                                                synchronized(this)
                                Waiting for
                                                    public char pop(char c)
                                object lock         {
                                                    synchronized(this)
                                                      {
                                                          idx--;
                                                          return data[idx];
                                                      }
                                                    }



     Ver. 1.0                          Session 13                            Slide 13 of 24
Java Programming Language
Releasing the Lock Flag


                The lock flag is released in the following events:
                   Released when the thread passes the end of the synchronized
                   code block
                   Released automatically when a break, return, or exception is
                   thrown by the synchronized code block




     Ver. 1.0                       Session 13                         Slide 14 of 24
Java Programming Language
Using synchronized


                • All access to delicate data should be synchronized.
                • Delicate data protected by synchronized should be
                  private.
                • The following two code segments are equivalent:
                   public void push(char c)
                   {
                      synchronized(this) {
                         // The push method code
                     }}
                   public synchronized void push(char c)
                   {
                       // The push method code
                   }

     Ver. 1.0                          Session 13                  Slide 15 of 24
Java Programming Language
Using synchronized (Contd.)


                  Thread State Diagram with Synchronization:

                                       Blocked                              Dead
                New
                          Unblocked                   Event Blocked


           start()                                                     run() Completes
                            Runnable Scheduler Running


                                                        Synchronized
                      Lock Acquired    Blocked in
                                      Object’s Lock
                                          Pool

     Ver. 1.0                          Session 13                          Slide 16 of 24
Java Programming Language
Deadlock


               A deadlock has the following characteristics:
                  It is two threads, each waiting for a lock from the other.
                  It is not detected or avoided.
                  Deadlock can be avoided by:
                     Deciding on the order to obtain locks
                     Adhering to this order throughout
                     Releasing locks in reverse order




    Ver. 1.0                         Session 13                                Slide 17 of 24
Java Programming Language
Thread Interaction


                • wait and notify Methods
                     Scenario:
                      • Consider yourself and a cab driver as two threads.
                     Problem:
                      • How do you determine when you are at your destination?
                     Solution:
                        You notify the cab driver of your destination and relax
                        The driver drives and notifies you upon arrival at your destination




     Ver. 1.0                           Session 13                                 Slide 18 of 24
Java Programming Language
Thread Interaction (Contd.)


                Thread interactions include:
                 – The wait() and notify() methods
                 – The pools:
                      Wait pool
                      Lock pool




     Ver. 1.0                      Session 13        Slide 19 of 24
Java Programming Language
Thread Interaction (Contd.)


                •   Thread State Diagram with wait() and notify() methods:

                                    Blocked
            New                                                            Dead
                       Unblocked                   Event Blocked


       start()                                                        run() Completes
                                     Scheduler
                        Runnable                   Running
                                                                        wait()

                    Lock Acquired                    Synchronized
                                    Blocked in                         Blocked in
                                     Object’s           notify() or
                                                                        Object’s
                                    Lock Pool          interrupt()
                                                                       Wait Pool
     Ver. 1.0                         Session 13                            Slide 20 of 24
Java Programming Language
Monitor Model for Synchronization


                Leave shared data in a consistent state
                Ensure programs cannot deadlock
                Do not put threads expecting different notifications in the
                same wait pool.




     Ver. 1.0                       Session 13                         Slide 21 of 24
Java Programming Language
Demonstration


               Lets see how to create a Java class that represents a separate
               thread of control flow.




    Ver. 1.0                         Session 13                      Slide 22 of 24
Java Programming Language
Summary


               In this session, you learned that:
                – Threads are a virtual CPU.
                – The three parts of at thread are CPU, Code, and Data.
                – Thread can be created by extend the class from Thread Class
                  or by implementing Runnable interface.
                – A Java program can have multiple threads.
                – Thread need to start by using start() method.
                – Various states of thread are runnable, running, and blocked.
                – sleep() method pauses the thread for given amount of time.
                – The thread dies when run() method completes.
                – sleep(), join(), and yield() methods put the thread on
                  hold.
                – Use getPriority() method to determine the current priority
                  of the thread.


    Ver. 1.0                       Session 13                         Slide 23 of 24
Java Programming Language
Summary (Contd.)


               – When multiple threads are working on shared data,
                 synchronized keyword should be used to maintain the
                 consistency of the data.
               – Deadlock is the situation where two threads, each waiting for a
                 lock from the other.
               – wait() and notify() are methods for thread
                 communication.




    Ver. 1.0                       Session 13                           Slide 24 of 24

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Basics of Java Concurrency
Basics of Java ConcurrencyBasics of Java Concurrency
Basics of Java Concurrency
 
Java adv
Java advJava adv
Java adv
 
Java Course 10: Threads and Concurrency
Java Course 10: Threads and ConcurrencyJava Course 10: Threads and Concurrency
Java Course 10: Threads and Concurrency
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
Java unit 12
Java unit 12Java unit 12
Java unit 12
 
Concurrency in Java
Concurrency in  JavaConcurrency in  Java
Concurrency in Java
 
Multi threading
Multi threadingMulti threading
Multi threading
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Java Multithreading and Concurrency
Java Multithreading and ConcurrencyJava Multithreading and Concurrency
Java Multithreading and Concurrency
 
04 threads
04 threads04 threads
04 threads
 
Java - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basicsJava - Concurrent programming - Thread's basics
Java - Concurrent programming - Thread's basics
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Byte code field report
Byte code field reportByte code field report
Byte code field report
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
L Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformaticsL Fu - Dao: a novel programming language for bioinformatics
L Fu - Dao: a novel programming language for bioinformatics
 
Java Concurrency Gotchas
Java Concurrency GotchasJava Concurrency Gotchas
Java Concurrency Gotchas
 
Threads in Java
Threads in JavaThreads in Java
Threads in Java
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
Exploring lambdas and invokedynamic for embedded systems
Exploring lambdas and invokedynamic for embedded systemsExploring lambdas and invokedynamic for embedded systems
Exploring lambdas and invokedynamic for embedded systems
 

Andere mochten auch

Web20 fortgeschrittene 2011_berlin
Web20 fortgeschrittene 2011_berlinWeb20 fortgeschrittene 2011_berlin
Web20 fortgeschrittene 2011_berlin
Jan Schmidt
 
CV Nguyen Huu Mai
CV Nguyen Huu MaiCV Nguyen Huu Mai
CV Nguyen Huu Mai
Mai Nguyen
 

Andere mochten auch (14)

Web20 fortgeschrittene 2011_berlin
Web20 fortgeschrittene 2011_berlinWeb20 fortgeschrittene 2011_berlin
Web20 fortgeschrittene 2011_berlin
 
OSHA Cert
OSHA CertOSHA Cert
OSHA Cert
 
Capitulo3
Capitulo3Capitulo3
Capitulo3
 
Caracteristicas
Caracteristicas Caracteristicas
Caracteristicas
 
Ventajas del Franquiciador y del Franquiciado
Ventajas del Franquiciador y del FranquiciadoVentajas del Franquiciador y del Franquiciado
Ventajas del Franquiciador y del Franquiciado
 
Java adapter
Java adapterJava adapter
Java adapter
 
La dignidad y los derechos humanos
La dignidad y los derechos humanosLa dignidad y los derechos humanos
La dignidad y los derechos humanos
 
ISO Lead Auditor Certificate
ISO Lead Auditor CertificateISO Lead Auditor Certificate
ISO Lead Auditor Certificate
 
LOS FRANQUICIADORES COMO FUENTE DE FINANCIAMIENTO
LOS FRANQUICIADORES COMO FUENTE DE FINANCIAMIENTOLOS FRANQUICIADORES COMO FUENTE DE FINANCIAMIENTO
LOS FRANQUICIADORES COMO FUENTE DE FINANCIAMIENTO
 
CV Nguyen Huu Mai
CV Nguyen Huu MaiCV Nguyen Huu Mai
CV Nguyen Huu Mai
 
SCM
SCMSCM
SCM
 
Como trabalhar com clientes difíceis e transformá los em clientes satisfeitos
Como trabalhar com clientes difíceis e transformá los em clientes satisfeitosComo trabalhar com clientes difíceis e transformá los em clientes satisfeitos
Como trabalhar com clientes difíceis e transformá los em clientes satisfeitos
 
Fractue fatigue and creep
Fractue fatigue and creepFractue fatigue and creep
Fractue fatigue and creep
 
Bozen Summerschool Digital Libraries
Bozen Summerschool Digital LibrariesBozen Summerschool Digital Libraries
Bozen Summerschool Digital Libraries
 

Ähnlich wie Java session13

Java session01
Java session01Java session01
Java session01
Niit Care
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
ketan_patel25
 
Java session05
Java session05Java session05
Java session05
Niit Care
 
Java class 6
Java class 6Java class 6
Java class 6
Edureka!
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
myrajendra
 

Ähnlich wie Java session13 (20)

Threads in JAVA
Threads in JAVAThreads in JAVA
Threads in JAVA
 
Java concurrency
Java concurrencyJava concurrency
Java concurrency
 
Java session01
Java session01Java session01
Java session01
 
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
Java Class 6 | Java Class 6 |Threads in Java| Applets | Swing GUI | JDBC | Ac...
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
java_threads.ppt
java_threads.pptjava_threads.ppt
java_threads.ppt
 
Threads
ThreadsThreads
Threads
 
Java Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPRECJava Notes by C. Sreedhar, GPREC
Java Notes by C. Sreedhar, GPREC
 
Java Notes
Java Notes Java Notes
Java Notes
 
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtugVk.amberfog.com gtug part1_introduction2_javaandroid_gtug
Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreadingLec7!JavaThreads.ppt java multithreading
Lec7!JavaThreads.ppt java multithreading
 
Lec7!JavaThreads.ppt
Lec7!JavaThreads.pptLec7!JavaThreads.ppt
Lec7!JavaThreads.ppt
 
Lecture10
Lecture10Lecture10
Lecture10
 
Java session05
Java session05Java session05
Java session05
 
Multi Threading
Multi ThreadingMulti Threading
Multi Threading
 
Java programming PPT. .pptx
Java programming PPT.                 .pptxJava programming PPT.                 .pptx
Java programming PPT. .pptx
 
Javamschn3
Javamschn3Javamschn3
Javamschn3
 
Java class 6
Java class 6Java class 6
Java class 6
 
Dead locks9cm604.39
Dead locks9cm604.39Dead locks9cm604.39
Dead locks9cm604.39
 

Mehr von Niit Care (20)

Ajs 1 b
Ajs 1 bAjs 1 b
Ajs 1 b
 
Ajs 4 b
Ajs 4 bAjs 4 b
Ajs 4 b
 
Ajs 4 a
Ajs 4 aAjs 4 a
Ajs 4 a
 
Ajs 4 c
Ajs 4 cAjs 4 c
Ajs 4 c
 
Ajs 3 b
Ajs 3 bAjs 3 b
Ajs 3 b
 
Ajs 3 a
Ajs 3 aAjs 3 a
Ajs 3 a
 
Ajs 3 c
Ajs 3 cAjs 3 c
Ajs 3 c
 
Ajs 2 b
Ajs 2 bAjs 2 b
Ajs 2 b
 
Ajs 2 a
Ajs 2 aAjs 2 a
Ajs 2 a
 
Ajs 2 c
Ajs 2 cAjs 2 c
Ajs 2 c
 
Ajs 1 a
Ajs 1 aAjs 1 a
Ajs 1 a
 
Ajs 1 c
Ajs 1 cAjs 1 c
Ajs 1 c
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Dacj 4 2-b
Dacj 4 2-bDacj 4 2-b
Dacj 4 2-b
 
Dacj 4 2-a
Dacj 4 2-aDacj 4 2-a
Dacj 4 2-a
 
Dacj 4 1-c
Dacj 4 1-cDacj 4 1-c
Dacj 4 1-c
 
Dacj 4 1-b
Dacj 4 1-bDacj 4 1-b
Dacj 4 1-b
 
Dacj 4 1-a
Dacj 4 1-aDacj 4 1-a
Dacj 4 1-a
 
Dacj 1-2 b
Dacj 1-2 bDacj 1-2 b
Dacj 1-2 b
 
Dacj 1-3 c
Dacj 1-3 cDacj 1-3 c
Dacj 1-3 c
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 

Java session13

  • 1. Java Programming Language Objectives In this session, you will learn to: Define a thread Create separate threads in a Java technology program, controlling the code and data that are used by that thread Control the execution of a thread and write platform independent code with threads Describe the difficulties that might arise when multiple threads share data Use wait and notify to communicate between threads Use synchronized to protect data from corruption Ver. 1.0 Session 13 Slide 1 of 24
  • 2. Java Programming Language Threads Threads are a virtual CPU. The three parts of the thread are: CPU Code Data A thread or execution context Ver. 1.0 Session 13 Slide 2 of 24
  • 3. Java Programming Language Creating the Thread • Extend the class from Thread Class. For example: public class HelloRunner extends Thread { //code } • Implement the Runnable interface. For example: class HelloRunner implements Runnable { //code } Ver. 1.0 Session 13 Slide 3 of 24
  • 4. Java Programming Language Creating the Thread (Contd.) Multithreaded programming has following characteristics: Multiple threads are from one Runnable instance. Threads share the same data and code. For example: Thread t1 = new Thread(r); Thread t2 = new Thread(r); Ver. 1.0 Session 13 Slide 4 of 24
  • 5. Java Programming Language Starting the Thread • Use the start() method • Place the thread in a runnable state Ver. 1.0 Session 13 Slide 5 of 24
  • 6. Java Programming Language Thread Scheduling Fundamental Thread State Diagram: Blocked Dead New Unblocked Event Blocked start() run() Completes Runnable Scheduler Running Ver. 1.0 Session 13 Slide 6 of 24
  • 7. Java Programming Language Thread Scheduling (Contd.) Thread Scheduling Example: public class Runner implements Runnable {public void run() {while (true){ // Do lots of interesting stuff // Give other threads a chance try{ One of Thread Thread.sleep(10); Scheduling Method }catch (InterruptedException e) { // This thread’s sleep was interrupted by another thread }}}} Ver. 1.0 Session 13 Slide 7 of 24
  • 8. Java Programming Language Terminating a Thread • The thread comes to the end of its run() method. • The thread throws an Exception or Error that is not caught. • Another thread calls one of the deprecated stop() methods. Ver. 1.0 Session 13 Slide 8 of 24
  • 9. Java Programming Language Basic Control of Threads Test Threads: isAlive() Access Thread Priority: getPriority() setPriority() Put Threads on Hold: Thread.sleep() // static method join() Thread.yield() // static method Ver. 1.0 Session 13 Slide 9 of 24
  • 10. Java Programming Language Basic Control of Threads (Contd.) • Use of join() method: public static void main(String[] args) { Thread t = new Thread(new Runner()); t.start(); // Do stuff in parallel with the other thread for a while // Wait here for the other thread to finish try { t.join(); } catch (InterruptedException e) { // the other thread came back early } // Now continue in this thread } Ver. 1.0 Session 13 Slide 10 of 24
  • 11. Java Programming Language The Object Lock Flag Every object has a flag that is a type of lock flag. The synchronized enables interaction with the lock flag. Object this Thread before synchronized(this) public void push (char c) { synchronized(this) { data[idx] = c; idx++; } } Ver. 1.0 Session 13 Slide 11 of 24
  • 12. Java Programming Language The Object Lock Flag (Contd.) Object this Thread after synchronized(this) public void push (char c) {synchronized(this) { data[idx] = c; idx++; } } Ver. 1.0 Session 13 Slide 12 of 24
  • 13. Java Programming Language The Object Lock Flag (Contd.) Object this lock flag missing Another thread, trying to execute synchronized(this) Waiting for public char pop(char c) object lock { synchronized(this) { idx--; return data[idx]; } } Ver. 1.0 Session 13 Slide 13 of 24
  • 14. Java Programming Language Releasing the Lock Flag The lock flag is released in the following events: Released when the thread passes the end of the synchronized code block Released automatically when a break, return, or exception is thrown by the synchronized code block Ver. 1.0 Session 13 Slide 14 of 24
  • 15. Java Programming Language Using synchronized • All access to delicate data should be synchronized. • Delicate data protected by synchronized should be private. • The following two code segments are equivalent: public void push(char c) { synchronized(this) { // The push method code }} public synchronized void push(char c) { // The push method code } Ver. 1.0 Session 13 Slide 15 of 24
  • 16. Java Programming Language Using synchronized (Contd.) Thread State Diagram with Synchronization: Blocked Dead New Unblocked Event Blocked start() run() Completes Runnable Scheduler Running Synchronized Lock Acquired Blocked in Object’s Lock Pool Ver. 1.0 Session 13 Slide 16 of 24
  • 17. Java Programming Language Deadlock A deadlock has the following characteristics: It is two threads, each waiting for a lock from the other. It is not detected or avoided. Deadlock can be avoided by: Deciding on the order to obtain locks Adhering to this order throughout Releasing locks in reverse order Ver. 1.0 Session 13 Slide 17 of 24
  • 18. Java Programming Language Thread Interaction • wait and notify Methods Scenario: • Consider yourself and a cab driver as two threads. Problem: • How do you determine when you are at your destination? Solution: You notify the cab driver of your destination and relax The driver drives and notifies you upon arrival at your destination Ver. 1.0 Session 13 Slide 18 of 24
  • 19. Java Programming Language Thread Interaction (Contd.) Thread interactions include: – The wait() and notify() methods – The pools: Wait pool Lock pool Ver. 1.0 Session 13 Slide 19 of 24
  • 20. Java Programming Language Thread Interaction (Contd.) • Thread State Diagram with wait() and notify() methods: Blocked New Dead Unblocked Event Blocked start() run() Completes Scheduler Runnable Running wait() Lock Acquired Synchronized Blocked in Blocked in Object’s notify() or Object’s Lock Pool interrupt() Wait Pool Ver. 1.0 Session 13 Slide 20 of 24
  • 21. Java Programming Language Monitor Model for Synchronization Leave shared data in a consistent state Ensure programs cannot deadlock Do not put threads expecting different notifications in the same wait pool. Ver. 1.0 Session 13 Slide 21 of 24
  • 22. Java Programming Language Demonstration Lets see how to create a Java class that represents a separate thread of control flow. Ver. 1.0 Session 13 Slide 22 of 24
  • 23. Java Programming Language Summary In this session, you learned that: – Threads are a virtual CPU. – The three parts of at thread are CPU, Code, and Data. – Thread can be created by extend the class from Thread Class or by implementing Runnable interface. – A Java program can have multiple threads. – Thread need to start by using start() method. – Various states of thread are runnable, running, and blocked. – sleep() method pauses the thread for given amount of time. – The thread dies when run() method completes. – sleep(), join(), and yield() methods put the thread on hold. – Use getPriority() method to determine the current priority of the thread. Ver. 1.0 Session 13 Slide 23 of 24
  • 24. Java Programming Language Summary (Contd.) – When multiple threads are working on shared data, synchronized keyword should be used to maintain the consistency of the data. – Deadlock is the situation where two threads, each waiting for a lock from the other. – wait() and notify() are methods for thread communication. Ver. 1.0 Session 13 Slide 24 of 24