Http://blog.sina.com.cn/s/blog_4b6047bc010007so.html correctly understanding and using swing thread model programming is the key to writing a flexible swing program. The swingworker introduced from Java SE 6 helps you easily write multi-threaded swing programs, improve the structure of your swing programs, and improve the flexibility of interface response. An excellent article on SDN (Sun Developer Network): improve application performance with swingworker in Java SE 6 demonstrates in detail how to use swingworker to improve swing applications. Translate it and share it with everyone.
Summary
A common error for desktop application programmers is misuse of the swing event scheduling thread (EDT ). They either access the UI component from a non-UI thread, or do not consider the event execution sequence, or execute time-consuming tasks on the EDT thread without using an independent task thread, as a result, the written application becomes slow and slow. Time-consuming computing and input/output (IO)-intensive tasks should not be run on Swing EDT. It is not easy to find the code for this problem, but Java SE 6 provides the javax. Swing. swingworker class, making it easier to correct this code.
This article demonstrates an example of using the swingworker class to create and manage task threads. It describes how to avoid writing a user interface that is slow, slow, and easy to lose response. This demo is called image search. It shows how to use the swingworker API to interact with and search for and download images on the website.
If you need to understand the basic concepts of swing UI, including event processing and listening UI programming, you can refer to the previous article or download and read the swing part of the Java tutorial from the sun official website.
Demo program Introduction The time-consuming task executed by image search is to access the services of the Flickr website. This task should not be executed on EDT. The image search program searches for the Flickr site, searches for images that match the search criteria entered by the user, and downloads thumbnails of matching images. When you select a thumbnail from the thumbnail list, it downloads the original image of the thumbnail. This demo program uses the swingworker class as the task thread to avoid executing these time-consuming tasks on EDT.
When you enter the query conditions, the program requests an image query on the Flickr website. If there are images that meet the query conditions, the maximum number of thumbnail images downloaded by the program is 100. You can modify the program to change the number of downloaded images. While searching and downloading images, a progress bar displays the search progress. Figure 1 shows the query field and progress bar: Figure 1. Search for the image and display the download progress
Each time the program successfully downloads a thumbnail, it is added to a jlist component and the image is added to the List after it arrives from the Flickr site. The program uses an instance of swingworker. The program can add each image to the list when it arrives without waiting for all the images to arrive. Figure 2 show the images in the list: Figure 2 match the thumbnail list
When you select an image from the list, the program downloads the original image and displays it below the list. When a large image is downloaded, another progress bar displays the download progress. Figure 3 shows the list and picture download progress bar. Figure 3 select a thumbnail to download a large image
Finally, after all the image data is downloaded, the program displays the image below the list.
The program uses swingworker to complete all image search and download tasks. In addition, the program demonstrates how to cancel a task and how to obtain immediate results before the task is completed. This program has two subclasses of swingworker: imagesearcher and imageretriever. The imagesearcher class is used to search for and retrieve thumbnails in the image list. The imageretriever class is used to download images of the original version when you select from the list. This section describes the main functions of the swingworker class. Figure 4 shows the overall appearance of the program. Figure 4 Use the swingworkere class to create a flexible response program interface
Review swing thread Basics A swing program generally has the following three types of threads:
* Initial thread)
* UI event scheduling thread (EDT)
* Worker thread)
Each program must have a main method, which is the entry of the program. This method runs on the initialization or startup thread. The initialization thread reads program parameters and initializes some objects. In many swing programs, this thread is mainly used to start the graphical user interface (GUI) of the program ). After the GUI is started, initialization of the thread ends for most event-driven desktop programs.
Only one swing program uses EDT. This thread is responsible for drawing and updating GUI components and responding to user interaction by calling the program's event processor. All event processing is performed on EDT. The interaction between the program and the UI component and its basic data model can only be performed on EDT. All Tasks running on EDT should be completed as soon as possible, so that the UI can respond to user input in a timely manner.
Pay attention to the following two points during swing programming:
1. Access to the UI component and its event processor from other threads may cause interface update and rendering errors.
2. Executing time-consuming tasks on EDT will cause the program to lose response, which will cause GUI events to be blocked and not processed in the queue.
3. Independent Task threads should be used to execute time-consuming computing or input/output-intensive tasks, such as files that communicate with databases, access website resources, and read/write large data volumes.
In short, the processing of any interference or delay UI events should only appear in the independent task thread; the interaction between the initialization thread or task thread and the swing component or its default data model is non-thread-safe.
The swingworker class helps you manage the interaction between the task thread and the swing EDT. Although swingworker cannot solve all the problems encountered in the concurrent thread, it does help to separate the swing EDT and the task thread, take responsibility for each of them: for EDT, it is to draw and update the interface and respond to user input. For the task thread, is to execute time-consuming tasks and I/O-intensive operations that are not directly related to the interface.
Use appropriate threadsInitialize the main method of the thread to run the program. This method can process many tasks. However, in a typical swing program, the main task is to create and run the application interface. The point when the program begins to transfer control to the UI. This is often the first place where problems occur during interaction with EDT.
The main class of the image search example is mainframe, Which is started from its main method. Many programs use the following method to start the interface, but this is a wrong method to start the UI:
Public class mainframe extends javax. Swing. jframe {
... Public static void main (string [] ARGs ){
New mainframe (). setvisible (true );
}
}
Although this error occurs at the beginning, it still violates the principle that other threads outside the EDT should not interact with the swing component. This error is especially easy to make. Although the thread synchronization problem is not immediately displayed, you must avoid writing it like this.
The UI should be correctly started as follows: public class mainframe extends javax. Swing. jframe {
... Public static void main (string [] ARGs ){
Swingutilities. invokelater (New runnable (){
Public void run (){
New mainframe (). setvisible (true );
}
});
}
}
Developers using netbeans ide should be familiar with this code, which is usually automatically generated by netbeans. Although this startup code is not directly related to swingworker, this programming paradigm is very important. The swingutilities class contains some static methods to help you interact with the UI components. The invokelater method means to execute its runnable task on EDT. The runnable interface defines tasks that can be executed as independent threads.
Use the invokelater method in the initialization thread to initialize the program interface correctly. As mentioned in the previous article, this method is executed asynchronously, that is, the call will return immediately. After the interface is created, most initialization threads basically end.
There are usually two ways to call this method:
* Swingutilities. invokelater
* Eventqueue. invokelater
Both methods are correct. You can select either method. In fact, swingutilities is just a thin encapsulation method, which directly calls eventqueue. invokelater. Because the swing framework itself often calls swingutilities, using swingutilities can reduce the classes introduced by the program.
Another way to put a task in EDT is swingutilities. invokeandwait, unlike invokelater, The invokeandwait method is blocked for execution. It executes the runnnable task on the EDT until the task is finished, and the method returns the call thread.
Invokelater and invokeandwait run their runnable tasks after all the events in the event dispatch queue are processed. That is to say, the two methods put the runnable task at the end of the event queue.
Note: although you can call invokelater on other threads or on EDT, do not call the invokeandwait method on the EDT thread! It is easy to understand that this will cause thread competition and the program will be deadlocked.
Use the EDT thread only for GUI tasksThe swing framework manages component rendering, updating, and thread processing on edts. As you can imagine, the event queue of this thread is very busy, and almost every GUI interaction and event is completed through it. Tasks in the event queue must be executed very quickly. Otherwise, the execution of other tasks will be blocked, blocking a lot of tasks waiting for execution in the queue, resulting in inflexible interface response, it makes users feel that the interface response speed is slow and they are not interested. Ideally, any task that takes more than 30 to 100 milliseconds should not be executed on EDT; otherwise, the user will be aware of the delay between the input and the interface response.
Fortunately, swing's performance will not be reduced simply because there are complex tasks, computing or input/output intensive tasks that need to be executed as GUI event processing tasks. After all, many desktop programs execute time-consuming tasks, such as processing spreadsheet formulas, querying databases across networks, and sending information to other programs over the Internet. Even with these tasks, the interface still allows users to feel flexible and fast responses. To write a program with flexible response, you need to create and manage threads independent of EDT.
In the image search program, if two events are processed completely on EDT, the interface response speed will be reduced: Image Search processing and image download processing.
Both event processing must access web services, which usually takes many seconds to respond. During this period, if the program interacts with Web Services on EDT, the user cannot cancel the search or interact with the interface. For example, neither of the two should run on EDT.
Figure 5 shows that EDT cannot process UI events between point A and point B. The time between point A and point B represents the I/O operation time when the program accesses the Web Service of the Flickr Website: Figure 5. EDT cannot respond to the UI event javax during Web Service Execution. swing. the swingworker class is a new class in Java SE 6. With swingworker, the program can start a task thread for asynchronous query and return the EDT thread immediately. Figure 6 shows that after swingworker is used, event processing returns immediately, allowing EDT to continue executing subsequent UI events. Figure 6. Using the task thread, the program can avoid executing I/O-intensive tasks on EDT (to be continued)
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.