An Introduction to Control Structures

Document Sample
An Introduction to Control Structures Powered By Docstoc
					Multithreading

      Chapter 5




                                      1
  Java Programming: Advanced Topics
                Objectives
• Explore the concepts of threads and
  multithreading
• Understand the lifecycle of a thread
• Create, start, and stop threads using
  java.lang.Thread and java.lang.Runnable
• Create daemon threads
• Use the JVM and java.util.Timer objects to
  schedule execution of java.util.TimerTask
  objects


                                                    2
                Java Programming: Advanced Topics
         Objectives (Cont.)
• Make your multithreaded programs robust
• Make class variables thread-safe using the
  ThreadLocal class
• Synchronize threads using the keyword
  synchronized
• Set up interthread communication using the
  methods Object.wait, Object.notify, and
  Object.notifyAll
• Create and use ThreadGroup objects that
  contain sets of threads
                                                   3
               Java Programming: Advanced Topics
   Threads and Multithreading
• Java includes the following features for
  multithreading:
  – The class java.lang.Thread
  – The interface java.lang.Runnable
  – The classes java.util.TimerTask and java.util.Timer
  – The class java.lang.ThreadLocal
  – Internal mechanism for thread synchronization
  – The methods wait, notify, and notifyAll inherited from
    java.lang.Object
  – The class java.lang.ThreadGroup

                                                             4
                   Java Programming: Advanced Topics
 Single-Threaded and
Multithreaded Programs




                                         5
     Java Programming: Advanced Topics
     The Lifecycle of a Thread
• Threads start running, pause, resume, and
  finally stop dynamically during program
  execution
• The states of all threads except the thread that
  the JVM is currently executing cannot change
• By default, the JVM tries to distribute control
  equally to all threads
• Threads with high priority values tend to
  preempt lower priority threads


                                                      6
                  Java Programming: Advanced Topics
 Creating and Running Threads
• A class can run as a separate thread if it extends
  the Thread class or implements the Runnable
  interface
• The Thread class provides the full infrastructure
  for multithreading, and implements Runnable
• All classes that implement Runnable must
  implement the method run
• Implementing Runnable is the more flexible and
  preferred approach


                                                     7
                 Java Programming: Advanced Topics
        Using the Thread Class
• Methods:
  –   Thread currentThread()
  –   int getPriority()
  –   void interrupt()
  –   boolean isDaemon()
  –   boolean isAlive()
  –   void join()
  –   void join( long milliseconds)




                                                         8
                     Java Programming: Advanced Topics
 Using the Thread Class (Cont.)
• Methods:
  –   void run()
  –   void setDaemon(boolean on)
  –   void setPriority(int priority)
  –   void sleep(long milliseconds)
  –   void start()
  –   void yield()




                                                         9
                     Java Programming: Advanced Topics
State Transition Diagram of a
           Thread




                                            10
        Java Programming: Advanced Topics
Sample Class That Extends
         Thread




                                           11
       Java Programming: Advanced Topics
 Using the Runnable Interface
• The java.lang.Runnable interface defines the
  protocol that must be followed by all threads
• The run() is the only method in the Runnable
  interface
• You must provide an implementation of the run
  method in every class that can be run as a
  spawned thread




                                                   12
               Java Programming: Advanced Topics
Sample Class That Implements
         Runnable




                                            13
        Java Programming: Advanced Topics
Stopping a Thread




                                       14
   Java Programming: Advanced Topics
     Creating Service Threads
• Daemon threads are threads that run in the
  background and typically have no associated
  user interface
  – setDaemon method: for a thread to specify that it is a
    daemon thread
  – isDaemon method: to determine whether a thread is a
    daemon thread




                                                        15
                   Java Programming: Advanced Topics
Using the JVM to Schedule Tasks
• The JVM creates background threads for you if
  you use the Timer and TimerTask classes from
  the java.util package to schedule tasks for future
  execution
• Class java.util.TimerTask implements Runnable
• Class java.util.Timer provides the facility to run a
  TimerTask object on a background thread
  generated by the JVM



                                                      16
                  Java Programming: Advanced Topics
A Class That Extends
 java.util.TimerTask




                                        17
    Java Programming: Advanced Topics
A Class That Creates a
 java.util.Timer Object




                                         18
     Java Programming: Advanced Topics
Wring Robust Multithreaded
        Programs
• Declare variables with the keyword volatile to
  suppress compiler optimizations that have
  the potential to lose or ignore changes made
  by different threads to the values of the
  variables
• Qualify the declaration of a method with the
  keyword synchronized to be run for a
  particular object or class by only one thread
  at a time

                                                  19
              Java Programming: Advanced Topics
     Making Variable Values
          Thread-Safe
• Thread-safe variables belong to one thread
  alone, and different threads have separate
  copies
• Local variables are thread-safe
• Synchronization provides the safety for
  instance variables
• Class variables are not thread-safe



                                                   20
               Java Programming: Advanced Topics
    Making Variable Values
     Thread-Safe (Cont.)
• Classes ThreadLocal and
  InheritableThreadLocal provide variables that
  are local to each thread and therefore
  thread-safe
• The ThreadLocal class can hold an object of
  any reference type




                                                   21
               Java Programming: Advanced Topics
   Making Variable Values
    Thread-Safe (Cont.)

• Methods of the ThreadLocal class:
  – Object get()
  – Object initialValue()
  – void set(Object value)




                                                   22
               Java Programming: Advanced Topics
A ThreadLocal Class Variable




                                            23
        Java Programming: Advanced Topics
A ThreadLocal Class Variable
          (Cont.)




                                            24
        Java Programming: Advanced Topics
A Class That Uses a ThreadLocal
            Variable




                                              25
          Java Programming: Advanced Topics
A Class That Uses a ThreadLocal
        Variable (Cont.)




                                              26
          Java Programming: Advanced Topics
    Synchronizing Threads
• Declare a class method with synchronized if
  only one thread at a time should be able to
  execute the method
• The mechanism of thread synchronization
  places locks on objects
• Locks are the Java concept for flags
  maintained by the operating system
• Object and class locks are independent



                                                  27
              Java Programming: Advanced Topics
A Synchronized Method




                                         28
     Java Programming: Advanced Topics
 When to Synchronize Code
• Synchronize code whenever the value of
  class or instance variables may change or
  methods may produce output to the same
  destination in code that can run on more than
  one thread
• To determine the level of synchronization
  that your application requires, consider how
  the threads within it share classes and
  objects


                                                  29
              Java Programming: Advanced Topics
Synchronizing Methods of Inner
           Classes
 • No special relationship exists between the
   synchronized methods of an inner class and
   its enclosing class
 • If a method of an inner class needs to
   participate in the synchronization of fields in
   the enclosing class, it should use a
   synchronized statement to obtain a lock for
   the enclosing class instance



                                                     30
                Java Programming: Advanced Topics
Synchronizing Methods of Inner
       Classes (Cont.)




                                             31
         Java Programming: Advanced Topics
Synchronizing Methods of Inner
       Classes (Cont.)




                                             32
         Java Programming: Advanced Topics
Communicating Between Threads
  • The Object class defines three methods for
    interthread communication:
    – void wait()
    – void notify (long timeout)
    – void notifyAll (long timeout, int nanoseconds)




                                                       33
                  Java Programming: Advanced Topics
     Making Threads Wait
• Call the wait method if a thread reaches an
  inactive state while waiting for input
• The wait method suspends the thread and
  gives other threads a chance to run
• Call wait in a loop:
  while ( condition ) { wait() }




                                                  34
              Java Programming: Advanced Topics
    Waking a Single Thread

• Call the notify method to wake up a thread
• The notify method wakes up a single thread
  that is blocked because it is in a wait state
• A synchronized method must still wait for the
  lock on the class or object




                                                   35
               Java Programming: Advanced Topics
       Waking All Threads

• The notifyAll method sends wake-up
  messages to all threads waiting for the lock
• All the threads go into a runnable state, but
  only one can actually acquire the lock and
  start running




                                                   36
               Java Programming: Advanced Topics
       Grouping Threads
• Collect Thread objects into ThreadGroup
  objects
• Thread objects in separate groups can be
  protected from each other
• Perform Thread operations on an entire
  group at once




                                                  37
              Java Programming: Advanced Topics
  Grouping Threads (Cont.)
• ThreadGroup objects provide security
  because a thread can modify another thread
  only if:
  – Both threads reside in the same group or
  – If the modified thread resides in a group that is
    nested within the group of the modifying thread
• After you create a thread, you cannot change
  its group



                                                        38
                Java Programming: Advanced Topics
                Summary
• A class can run as a separate thread if it
  extends the Thread class or implements the
  Runnable interface
• All classes that implement Runnable must
  implement the method run
• The Thread class provides methods to control
  your threads, including yield, sleep, and
  setPriority
• Daemon threads are threads that run in the
  background

                                                   39
               Java Programming: Advanced Topics
           Summary (Cont.)
• Use the Timer and TimerTask classes from the
  java.util package to schedule tasks for future
  execution
• Declare a class method with synchronized if only
  one thread at a time should be able to execute
  the method
• For interthread communication the wait, notify,
  and notifyAll methods are used
• For greater security and convenience, you can
  collect Thread objects into ThreadGroup objects

                                                    40
                Java Programming: Advanced Topics

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:0
posted:4/19/2013
language:English
pages:40