Documentos de Académico
Documentos de Profesional
Documentos de Cultura
• 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
• Thread Support
Java supports multithreading at the language/JVM level.
Any platform supporting Java supports multithreading.
• Implementations
• Class/Interface
A Thread class for sub-classing threaded-classes;
A Runnable interface to work around single-inheritance;
• Thread Synchronization
The synchronized keyword for mutual exclusion;
Special methods (wait(), notify(), etc.) of the Object class for
threads coordination;
• Thread Management
A ThreadGroup class for managing threads in groups;
A ThreadLocal class for implementing thread-local storage.
The new thread will start execution from the run() method.
Thread terminates when returned from run().
The new thread will start execution from the run() method.
Thread terminates when returned from run().
• Thread Priorities
Initial priority is the same as the creating thread.
Ranges of thread priority:
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.
Note that the thread priority affects scheduling of threads within the
same process only.
The JVM does not guarantee anything based on thread priorities.
Thread #1
Thread #3 Thread #3
Thread #4
Thread4.join();
Thread3.join();
Thread2.join();
• Mutual Exclusion
How?
• 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)
• Mutual Exclusion
Synchronization on a Block Level
class ThreadSend {
static Object Lock = new Object(); // for sync
public void doSomething( ) {
// …
synchronized(Lock) {
// protected code …
}
}
}
• Mutual Exclusion
Synchronization on a Block Level
blocked
Thread 1
synchronized(Lock) {
Thread 2 ...
}
Thread 3
class ThreadSend {
static Object Lock = new Object(); // for sync
// ...
}
• Mutual Exclusion
Synchronization on a Method Level
• Ensures only one thread can call an object’s method at a time.
• Mutual Exclusion
Synchronization on a Method Level
blocked
Thread 1 (ts1)
ts1.doSomething () {
Thread 2 (ts1) ...
}
Thread 3 (ts2)
ts2.doSomething () {
...
}
• Mutual Exclusion
Synchronization on a Class Level
• Ensures only one thread can call a class method at a time.
• Mutual Exclusion
Synchronization on a Class Level
blocked
Thread 1 (ts2)
ThreadSend.doSomething () {
Thread 2 (ts2) ...
}
Thread 3 (ts1)
FIFO Queue
Producer Consumer
Consumer
Consumer
• Producer-Consumer(s) Synchronization
Problem #2
• Producer needs to be suspended if the queue is full.
FIFO Queue
Producer X Consumer
Consumer
Consumer
FIFO Queue
Producer Consumer
Consumer
Consumer
• Producer-Consumer(s) Synchronization
Problem #3
• Consumer needs to be suspended if the queue is empty.
FIFO Queue
Producer X Consumer
Consumer
Consumer
FIFO Queue
Producer Consumer
Consumer
Consumer
• Producer-Consumer(s) Synchronization
Solution 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.
Semaphore Constructors
Semaphore (int initial_count)
Semaphore (int initial_count, boolean fairness_flag)
• Pitfall #1
The 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:
• Pitfall #2
The 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?)
• Pitfall #2
Example - Periodically Update Statistics
• Incorrect implementation
while (bIsRunning) {
UpdateStat(); // update stat display
sleep(100); // wait for 100 ms
}
} offending code
// Statistics Update Function //
public void UpdateStat()
{
// ...
// # of Packets Transferred
str = String.valueOf(num_transferred);
m_JLabel_PacketsTransferred.setText(str);
// ...
}
• Pitfall #2
Solution
• 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.
• Pitfall #2
Example - Periodically Update Statistics
• Correct implementation
TimerThread
invokeLater(…)
Swing
UpdateCode
(implements Runnable)
• Pitfall #2
Example - Periodically Update Statistics
• Correct implementation
// Constructor
TimerThread(int refresh_interval, Runnable update_code) {
m_iRefreshInterval = refresh_interval;
m_UpdateCode = update_code;
m_bToQuit = false;
}
// Set Function
void QuitUpdate() { m_bToQuit = true; }
• Pitfall #2
Example - Periodically Update Statistics
• Correct implementation
// Constructor
public JNetProbe() {
initComponents ();
pack ();
// ...
m_TimerThread = new TimerThread(100, this);
m_TimerThread.start();
}
}