View
436
Download
1
Category
Preview:
Citation preview
IEG 4180IEG 4180Network Software Design and ProgrammingNetwork Software Design and Programming
Java Java MultithreadMultithread ProgrammingProgramming
IEG4180: Network Software Design and Programming - Java Multithread Programming 2
Copyright Jack Y. B. LeeAll Rights ReservedContents
• 1. Introduction• 2. Java Thread APIs• 3. Creating a New Thread• 4. Thread Scheduling• 5. Thread Synchronization• 6. Thread Coordination• 7. Swing and Multithreading• References
IEG4180: Network Software Design and Programming - Java Multithread Programming 3
Copyright Jack Y. B. LeeAll Rights Reserved1. Introduction
• Thread SupportJava supports multithreading at the language/JVM level.Any platform supporting Java supports multithreading.
• Implementations
Java Virtual Machine
Java Multithread Application
Java Thread Classes
Java Virtual Machine
Java Multithread Application
Operating System Native Thread API(e.g., POSIX Pthreads, Win32 threads)
Java Thread Classes
Internal Implementationof Threads (green threads)
JVM-Implemented Threads Using Native Threads
IEG4180: Network Software Design and Programming - Java Multithread Programming 4
Copyright Jack Y. B. LeeAll Rights Reserved2. Java Thread APIs
• Class/InterfaceA Thread class for sub-classing threaded-classes;A Runnable interface to work around single-inheritance;
• Thread SynchronizationThe synchronized keyword for mutual exclusion;Special methods (wait(), notify(), etc.) of the Object class for threads coordination;
• Thread ManagementA ThreadGroup class for managing threads in groups;A ThreadLocal class for implementing thread-local storage.
IEG4180: Network Software Design and Programming - Java Multithread Programming 5
Copyright Jack Y. B. LeeAll Rights Reserved3. Creating a New Thread
• Method 1: Subclassing the Thread ClassStep 1 - Subclass from the Thread class
Step 2 - Create the new thread
class ThreadSend extends Thread {public void run( ) {
// …}
}
The new thread will start execution from the run() method.Thread terminates when returned from run().
ThreadSend sender = new ThreadSend(); // Create the thread objectsender.start(); // Create the new thread
The start() method is inherited from class Thread.This call start the new thread’s execution from the run() method.
IEG4180: Network Software Design and Programming - Java Multithread Programming 6
Copyright Jack Y. B. LeeAll Rights Reserved3. Creating a New Thread
• Method 2: Implementing the Runnable InterfaceStep 1 - Implements the Runnable interface
Step 2 - Start the new thread via a Thread object
class ThreadSend implements Runnable {public void run( ) {
// …}
}
The new thread will start execution from the run() method.Thread terminates when returned from run().
Thread thread_1 = new Thread(new ThreadSend());thread_1.start();
Creates a new Thread object and pass it the ThreadSend object.This can be done because the Thread object is expecting a Runnable object.
IEG4180: Network Software Design and Programming - Java Multithread Programming 7
Copyright Jack Y. B. LeeAll Rights Reserved3. Creating a New Thread
• Subclassing Thread v.s. Implementing RunnableImplementing the Runnable interface is required if your class already has a superclass.Otherwise subclassing Thread is generally simpler.
• You can call Thread’s methods such as sleep() and setPriority() within the run() method.
Workaround using Thread.currentThread():
class ThreadSend implements Runnable {public void run( ) {
// sleep(1000); <- this won’t work.Thread.currentThread().sleep(1000); // this is ok.
}}
You can call Thread.currentThread() anywhere because it is a static method.
IEG4180: Network Software Design and Programming - Java Multithread Programming 8
Copyright Jack Y. B. LeeAll Rights Reserved4. Thread Scheduling
• Thread PrioritiesInitial priority is the same as the creating thread.Ranges of thread priority:
Methods for get/set thread priority:
Note that the thread priority affects scheduling of threads within the same process only.The JVM does not guarantee anything based on thread priorities.
public final int getPriority()
public final void setPriority(int newPriority)
static int MAX_PRIORITY - The maximum priority that a thread can have.static int MIN_PRIORITY - The minimum priority that a thread can have.static int NORM_PRIORITY - The default priority that is assigned to a thread.
IEG4180: Network Software Design and Programming - Java Multithread Programming 9
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Waiting for Threads To Terminatevoid Thread::join()
void Thread::join(long millis)
void Thread::join(long millis, int nanos)
Thread #1
Thread #2
Thread #3
Thread #4
Thread #3
Thread #2Thread #2
Thread4.join();Thread3.join();Thread2.join();
IEG4180: Network Software Design and Programming - Java Multithread Programming 10
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionHow?
• Java supports a synchronized keyword.• It’s applicable to a class, a method, and a block of code.
Object-based Synchronization• Any Java objects can be used for synchronization.• Built-in types (int, float, etc.) cannot be used.
synchronize(obj)
An object is being used as a mutex for synchronization.The object (mutex) can be acquired by at most one thread at any one time.
IEG4180: Network Software Design and Programming - Java Multithread Programming 11
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Block Level
class ThreadSend {static Object Lock = new Object(); // for syncpublic void doSomething( ) {
// … synchronized(Lock) {
// protected code …}
}}
At anytime at most one thread can enter this block of code.This is true even if multiple instances of ThreadSend have been created. (Why?)
IEG4180: Network Software Design and Programming - Java Multithread Programming 12
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Block Level
Thread 1
Thread 2
Thread 3
synchronized(Lock) { ...
}
blocked
class ThreadSend {static Object Lock = new Object(); // for sync// ...
}
Lock is static, so only one instance exists regardless of number of ThreadSend instances.
IEG4180: Network Software Design and Programming - Java Multithread Programming 13
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Method Level
• Ensures only one thread can call an object’s method at a time.
• So if there are two instances of ThreadSend, then the doSomething() method in the two instances can be executed by two different threads concurrently.
class ThreadSend extends Thread {synchronized void doSomething( ) {
// …}
}
This is equivalent to synchronized(this).
IEG4180: Network Software Design and Programming - Java Multithread Programming 14
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Method Level
Thread 1 (ts1)
Thread 2 (ts1)
Thread 3 (ts2)
ts1.doSomething () { ...
}
blocked
ThreadSend ts1 = new ThreadSend();ThreadSend ts2 = new ThreadSend();// ...
ts2.doSomething () { ...
}
Thread 2 and 3 can concurrently run doSomething()because two ThreadSend instances are used.
IEG4180: Network Software Design and Programming - Java Multithread Programming 15
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Class Level
• Ensures only one thread can call a class method at a time.
• So even if there are two instances of ThreadSend, the doSomething() method still can only be executed by at most one thread only.
class ThreadSend extends Thread {static synchronized void doSomething( ) {
// …}
}
This is equivalent to synchronized(Class.forName(ThreadSend)).
IEG4180: Network Software Design and Programming - Java Multithread Programming 16
Copyright Jack Y. B. LeeAll Rights Reserved5. Thread Synchronization
• Mutual ExclusionSynchronization on a Class Level
ThreadSend.doSomething () { ...
}
ThreadSend ts1 = new ThreadSend();ThreadSend ts2 = new ThreadSend();// ...
Thread 1 (ts2)
Thread 2 (ts2)
Thread 3 (ts1)
blocked
IEG4180: Network Software Design and Programming - Java Multithread Programming 17
Copyright Jack Y. B. LeeAll Rights Reserved6. Threads Coordination
• The Producer-Consumer Model Revisited
Problem #1 - Mutual exclusion in accessing the queue.Solution
• Use the Java synchronized mechanism to control access to the queue object.
ProducerFIFO Queue
ConsumerConsumerConsumer
The producer runs in a separate thread.
The consumer(s) also runs in separate threads.
IEG4180: Network Software Design and Programming - Java Multithread Programming 18
Copyright Jack Y. B. LeeAll Rights Reserved6. Threads Coordination
• Producer-Consumer(s) SynchronizationProblem #2
• Producer needs to be suspended if the queue is full.
• And it needs to be waked up once the queue has vacant space.
ProducerFIFO Queue
ConsumerConsumerConsumerX
ProducerFIFO Queue
ConsumerConsumerConsumer
IEG4180: Network Software Design and Programming - Java Multithread Programming 19
Copyright Jack Y. B. LeeAll Rights Reserved6. Threads Coordination
• Producer-Consumer(s) SynchronizationProblem #3
• Consumer needs to be suspended if the queue is empty.
• And it needs to be waked up once the queue becomes non-empty.
ProducerFIFO Queue
ConsumerConsumerConsumerX
ProducerFIFO Queue
ConsumerConsumerConsumer
IEG4180: Network Software Design and Programming - Java Multithread Programming 20
Copyright Jack Y. B. LeeAll Rights Reserved6. Threads Coordination
• Producer-Consumer(s) SynchronizationSolution to Problem #2 & #3
• The Java Object class implements several special methods for inter-thread synchronization: wait(), notify().
• wait()
Causes current thread to wait until another thread invokes the notify() method for this object.
• notify()
Wakes up a single thread that is waiting on this object's monitor. If multiple threads are waiting on this object, one of them is chosen to be awakened.
• Using these functions one can implement a semaphore class.
IEG4180: Network Software Design and Programming - Java Multithread Programming 21
Copyright Jack Y. B. LeeAll Rights Reserved6. Threads Coordination
• The java.util.concurrent.Semaphore ClassNew in JDK 5.0 (formerly 1.5) released in September 2004Semaphore Methods
Semaphore Constructors
Semaphore (int initial_count)
Semaphore (int initial_count, boolean fairness_flag)
Semaphore::Acquire()
Semaphore::Acquire(int how_many)
Semaphore::Release()
Semaphore::Release(int how_many)
Blocks until successful.
If set to true blocked-acquiring-threads will be released in first-in-first-out order, otherwise in unpredictable order (likely last-in-first-out).
IEG4180: Network Software Design and Programming - Java Multithread Programming 22
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #1The Swing library manages GUI components in a thread (event-dispatching thread) separate from your application’s threads.Methods in listener objects are called by Swing in the context of the event-dispatching thread:
• Access to shared data structures with the event-dispatching thread may have to be synchronized.
Swing(runs in a separate thread)
class MyWinListener implements WindowListener {public void windowClosing(WindowEvent e) {
// your processing code are being run// in the event-dispatching thread!
}}
IEG4180: Network Software Design and Programming - Java Multithread Programming 23
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2The Swing library is NOT thread-safe!You may not call the Swing library such as creating, or updating GUI components in your own thread, except within the application main() method (or applet init() method).Calling the Swing library within a listener method is ok. (why?)
IEG4180: Network Software Design and Programming - Java Multithread Programming 24
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2Example - Periodically Update Statistics
• Incorrect implementation
public class JNetProbe extends javax.swing.JFrame implements Runnable {// From the Runnable Interfacepublic void run() {
while (bIsRunning) {UpdateStat(); // update stat displaysleep(100); // wait for 100 ms
}}// Statistics Update Function //public void UpdateStat(){
// ... // # of Packets Transferredstr = String.valueOf(num_transferred);m_JLabel_PacketsTransferred.setText(str);// ...
}
public static void main (String args[]) {// ...// Start a new thread for statistics updateThread statUpdate = new Thread(this);// ...
}}
Run
s in
the statUpdate
thre
ad.
offending code
IEG4180: Network Software Design and Programming - Java Multithread Programming 25
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2Solution
• Swing allows another thread to manually generate an event for processing in the event-dispatching thread.
• Two methods in the javax.swing.SwingUtilities class:static void invokeAndWait(Runnable doRun)
» Causes doRun.run() to be executed synchronously on the event-dispatching thread.
static void invokeLater(Runnable doRun)
» Causes doRun.run() to be executed asynchronously on the event-dispatching thread.
class doRun implements Runnable {public void run() {
// This will be run within the event-dispatching thread.// Updating GUI here will be safe.
}}
IEG4180: Network Software Design and Programming - Java Multithread Programming 26
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2Example - Periodically Update Statistics
• Correct implementation
TimerThread
Swing
invokeLater(…)
UpdateCode(implements Runnable)
context of event-dispatching threadcontext of timer thread
IEG4180: Network Software Design and Programming - Java Multithread Programming 27
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2Example - Periodically Update Statistics
• Correct implementation
class TimerThread extends Thread {
// ConstructorTimerThread(int refresh_interval, Runnable update_code) {
m_iRefreshInterval = refresh_interval;m_UpdateCode = update_code;m_bToQuit = false;
}
// Set Functionvoid QuitUpdate() { m_bToQuit = true; }
// Thread entry functionpublic void run() {
// Generates one event to m_UpdateCode every m_RefreshInterval millisecondswhile (!m_bToQuit) {
javax.swing.SwingUtilities.invokeLater(m_UpdateCode);try {
sleep(m_iRefreshInterval);} catch (Exception e) { }
}}
}
IEG4180: Network Software Design and Programming - Java Multithread Programming 28
Copyright Jack Y. B. LeeAll Rights Reserved7. Swing and Multithreading
• Pitfall #2Example - Periodically Update Statistics
• Correct implementation
public class JNetProbe extends javax.swing.JFrame implements Runnable {
// To-be invoked from the event-dispatching threadpublic void run() {
UpdateStat(); // update stat display}
// Constructorpublic JNetProbe() {
initComponents ();pack ();
// ...m_TimerThread = new TimerThread(100, this);m_TimerThread.start();
}}
IEG4180: Network Software Design and Programming - Java Multithread Programming 29
Copyright Jack Y. B. LeeAll Rights ReservedReferences
• Doug Lea, Concurrent Programming in Java - Design Principles and Patterns, Second Edition, Sun Microsystems Press, 1999.
• Bil Lewis and Daniel J. Berg, Multithreaded Programming with Java Technology, Sun Microsystems Press, 2000.
Recommended