Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Programming: Advanced Topics

Similar presentations


Presentation on theme: "Java Programming: Advanced Topics"— Presentation transcript:

1 Java Programming: Advanced Topics
Multithreading Chapter 5 Java Programming: Advanced Topics

2 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 Java Programming: Advanced Topics

3 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 Java Programming: Advanced Topics

4 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 Java Programming: Advanced Topics

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

6 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 Java Programming: Advanced Topics

7 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 Java Programming: Advanced Topics

8 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) Java Programming: Advanced Topics

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

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

11 Sample Class That Extends Thread
Java Programming: Advanced Topics

12 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 Java Programming: Advanced Topics

13 Sample Class That Implements Runnable
Java Programming: Advanced Topics

14 Java Programming: Advanced Topics
Stopping a Thread Java Programming: Advanced Topics

15 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 Java Programming: Advanced Topics

16 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 Java Programming: Advanced Topics

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

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

19 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 Java Programming: Advanced Topics

20 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 Java Programming: Advanced Topics

21 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 Java Programming: Advanced Topics

22 Making Variable Values Thread-Safe (Cont.)
Methods of the ThreadLocal class: Object get() Object initialValue() void set(Object value) Java Programming: Advanced Topics

23 A ThreadLocal Class Variable
Java Programming: Advanced Topics

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

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

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

27 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 Java Programming: Advanced Topics

28 Java Programming: Advanced Topics
A Synchronized Method Java Programming: Advanced Topics

29 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 Java Programming: Advanced Topics

30 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 Java Programming: Advanced Topics

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

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

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

34 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() } Java Programming: Advanced Topics

35 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 Java Programming: Advanced Topics

36 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 Java Programming: Advanced Topics

37 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 Java Programming: Advanced Topics

38 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 Java Programming: Advanced Topics

39 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 Java Programming: Advanced Topics

40 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 Java Programming: Advanced Topics


Download ppt "Java Programming: Advanced Topics"

Similar presentations


Ads by Google