Multithreading with GUI l All Swing applications have a single thread, l called the event dispatch thread, to handle l l All tasks that require interaction with an application’s GUI l are placed in an event queue and l l interactions with the application’s GUI components. are executed sequentially by the event dispatch thread. Swing GUI components are not thread safe. l Thread safety in GUI applications is achieved by ensuring that l Swing components are accessed from only a single thread
Swing. Worker class l Java SE 6 provides class Swing. Worker l l to perform long-running computations in a worker thread and to update Swing components from the event dispatch thread l l It implements the Runnable interface, meaning that a l Swing. Worker object can be scheduled to execute l l based on the computations’ results. in a separate thread. Some common Swing. Worker methods are described next
Swing. Worker methods
Example I: Fibonacci Calculator l Class Background. Calculator l extends Swing. Worker l l Method do. In. Background l computes the nth Fibonacci number in a worker thread l l overriding the methods do. In. Background and done. and returns the result. Method done displays the result in a JLabel.
Comments on Fibonacci Calculator Project l Swing. Worker is a generic class. l The first type parameter indicates l l the type returned by the do. In. Background method; the second indicates l the type that is passed between l l the publish and process methods to handle intermediate results. When method execute is called l the object is scheduled for execution in a worker thread.