Java Reference
In-Depth Information
Swing and threads
20
Threads are parts of an application which run in parallel. Although most applications
in this topic seem to be single-threaded, they are not. Any application involving a
graphical surface is automatically multi-threaded. A number of threads are gen-
erated by the runtime system, and these run in parallel to the program code of
the actual application. These threads usually run unnoticed by the user. In some
cases, however, this concurrency can cause problems. We want to address the most
frequent of these problems in this chapter.
To understand the role of threads in Java applications with graphical user inter-
faces, let us remember the life cycle of such applications. As mentioned in the
introduction, the GUI for the application is created in the start-up phase. Once
the GUI is made visible the application is event driven . That is, it is steered by
events triggered by the user (or by other applications). Such an event is, for exam-
ple, pressing a button. Events are detected by the runtime system, which informs
the appropriate listener of the application. For a button it would be an action lis-
tener. This listener then executes a method that contains the code for reacting to
the event. For action listeners this is method actionPerformed .
The administration of the events is done by a thread that is started unknown
to the user, the so-called event thread , sometimes also called event dispatching
thread .Wedescribe this mechanism in the following and then address some prob-
lems it might cause. We would like to emphasize that this chapter is not meant as
an introduction to concurrent programming with threads in Java. The reader is as-
sumed to know the basics on threads or to look them up in the Java documentation
or in tutorials on the web.
20.1
Event thread and event queue
Every Java application starts at least one thread, the main thread . Almost all
code that the programmer writes is executed in this thread. For an application
with a GUI the event thread is created and runs in parallel to the main thread.
It administers the incoming events. If the events come at a high rate or it takes
too long to process them, then a new event might occur before the previous one
has been entirely processed. Therefore the event thread uses an event queue to
Search WWH ::




Custom Search