Professional Documents
Culture Documents
Event-dispatching thread
• By default all AWT and Swing-based
applications start off with two threads.
– One is the main application thread which handles
Concurrency in Java Swing execution of the main() method.
– The other, referred to as the event-dispatching
thread, is responsible for handling events, painting,
and layout.
• All events are processed by the listeners that
receive them within the event-dispatching
thread.
– the code you write inside the body of an
actionPerformed() method is executed within the
event-dispatching thread automatically
1 2
event queue
components at the same time, java.awt.EventQueue).
the components might end up in • The queue gets filled up
an inconsistent state, e.g. half in a serial fashion.
of the panel is repainted • Each request takes its
according to the instructions turn executing event-
from one thread while the other handling code.
half might be drawn according – All events are
to the instructions from processed serially
another thread Event processed
draw by the thread
for painting square
3 4
1
14/04/2012
2
14/04/2012
3
14/04/2012
4
14/04/2012
5
14/04/2012
class MySwingWorker extends SwingWorker<Double, Double> { • When the “compute” button is clicked, a SwingWorker
type object is created and is registered with runtime.
public Double doInBackground() { • The runtime creates a worker thread to run the
… doInBackground method of the SwingWorker object.
while (i > 0) {
• When the publish method is called by the SwingWorker
…
object, a event is added to the system event queue.
publish(new Double(z));
} – The event-dispatch thread process the event of the
SwingWorker object by executing the process method of
return new Double(z); the SwingWorker object.
}
– The process method does not contain any long-running
computation. Thus, it won’t freeze the GUI.
protected void process(java.util.List<Double> numbers) {
Double num = numbers.get(numbers.size() - 1);
• When the “counter” button is clicked, an event is added
computeText.append(num.toString()+"\n");
to the system event queue.
} – The event will be processed by the event-dispatch thread.
• When the SwingWorker object’s doInBackground
protected void done() { method terminates, an event is added to the system
… event queue.
computeText.append("done "+computeCount+"\n"); – The event will be processed by the event-dispatch thread
} by executing the done method of the SwingWorker object.
} 23 24
6
14/04/2012