Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Thread Programming

Similar presentations


Presentation on theme: "Java Thread Programming"— Presentation transcript:

1 Java Thread Programming
Paul Hyde

2 Purpose Review what we’ve learned Add details

3 Java Threads display GUI JVM event handler main garbage collection
Allows better user interaction (e.g., don’t wait for graphics to load), simulation of simultaneous activities (e.g., edit & print document), other activities while waiting for I/O garbage collection Second thread always running in JVM When you are writing graphical programs that use AWT or Swing, multithreading is a necessity for all but the most trivial programs.

4 Thread costs Memory resources. Each thread has two execution call stacks. Processor overhead required for context switch. Work to start, stop and destroy a thread. Consideration for brief background tasks (e.g., checking for new ).

5 Java & Threads Important feature built into core of language
Thread and ThreadGroup classes in java.lang package Object has wait() and notify() methods for inter-thread communication synchronized keyword used to control concurrent access to data garbage collection frees developer from knowing when memory for an object can be released.

6 Simple Thread example Steps to spawn a new thread:
Extend java.lang.Thread class Override run() method in subclass Create instance of new class Invoke start() method on instance NOTE: implementing Runnable often works better in real applications, but extending Thread is a simple way to get started with multi-threading.

7 <<interface>>
Example continued public class TwoThreads extends Thread { …. } <<interface>> Runnable Object Thread TwoThreads

8 Example continued public class TwoThreads extends Thread {
public void run() { for (int i=0; i<10; ++i) System.out.println(“running”); } // elsewhere, e.g., in main TwoThreads tt = new TwoThreads(); tt.start(); somethingElse(); // invokes run of TwoThread as soon as thread scheduler // can get to it, may be before or after somethingElse // Order of statement execution between two threads is // indeterminate – dangerous if specific order is needed // for correctness!

9 currentThread In some programs it’s possible for more than one Thread to execute the same method. The currentThread() method can be used to access the currently executing thread.

10 start & isAlive start() means thread is ready, run() method should be executed at earliest convenience isAlive() determines whether thread has been started and is still running

11 sleep example A thread cannot put another thread to sleep
A sleeping thread can be interrupted (another thread calls interrupt), so must catch InterruptedException Better than a “busy loop” because it doesn’t use processor cycles

12 Gracefully stopping Threads (chapter 5)
Threads die a natural death when run() method ends e.g., (for int i=0; i<10; i++) { …. } // run() ends But thread run methods often contain an infinite loop May need to pause a thread, e.g., if executing a lengthy operation May need to terminate the thread stop() has been deprecated because it can lead to corrupted data. Releases locks, which may leave data in invalid state. – so what to do?

13 Alternative to stop() include a volatile boolean stopRequested in thread class set stopRequested to false at beginning of run() while loop in run() checks status of stopRequested provide method to set stopRequested to true when appropriate

14 volatile* for efficiency, default is to reconcile shared values when thread enters or leaves a synchronized block of code. Default is good when only one thread interacts with member variables of an object; can be a problem if two threads interact. volatile forces threads to reread the variable’s value from memory every time threads must write values back to shared memory as soon as they occur (no caching) Use volatile on member variables that can be accessed by two or more threads unless all threads access the variables within synchronized blocks. * not emphasized, you may encounter it

15 More on volatile The volatile keyword was introduced to the language as a way around optimizing compilers. Take the following code for example: class VolatileTest { boolean flag; public void foo() { flag = false; if(flag) { //this could happen } } } An optimizing compiler might decide that the body of the if statement would never execute, and not even compile the code. If this class were accessed by multiple threads, flag could be set by another thread after it has been set in the previous code, but before it is tested in the if statement. Declaring variables with the volatile keyword tells the compiler not to optimize out sections of code by predicting the value of the variable at compile time.

16 synchronized ensures that only one thread is allowed inside a method at one time. Can also synchronize blocks Collections are not inherently thread safe (decision based on performance).


Download ppt "Java Thread Programming"

Similar presentations


Ads by Google