Use Swing Worker thread

zhaozj2021-02-16  121

Using Swing Worker Thread - New Method for Execute Background Task Fooosleeper Translation (Participation: 1563, Expert Count: 590) Published: 2003-7-11 5:01 PM Updated: 2003-7-13 11:21 PM Version: 1.0 Read: 2974 times

Author: Hans Muller, Kathy Walrath translation: Guo Xiaogang (foosleeper@163.net) from java.sun.com original article gives some examples of the use of the SwingWorker. The purpose of the SwingWorker class is to implement a background thread that allows you to perform some time-consuming operations without affecting the performance of your program's GUI. For some basic information about the SwingWorker class, see "Threads and SWING". Note: In September 2000 we modified this article and its examples to apply to a new version of SwingWorker class. This version of the SwingWorker class fixes some subtle thread bugs. The thread is a basic solution to the Swing program that performs some fees or blockable operations. For example, if your application wants to send a database request or load a file according to the menu item selected by the user, then you should do this in a separate thread. This article describes the ways to complete the above work in an isolated Worker thread. This article includes the following main contents:

SwingWorker Class: This section tells you how to download the SwingWorker class and describe the use of the SwingWorker class. Introduced the interrupt () method of the SwingWorker class. Examples of introducing a Worker thread: Demos an application that uses the SwingWorker class. Example 1: Interrupt a Swing Worker Thread: Interpret how to use the interrupt () method to interrupt the Worker thread. Example 2: Feedback from Swing Worker thread to the user: an example of an enhancement, add a mode dialog to prompt user input. Overview: SwingWorker class Because the SwingWorker class is not part of the Java release, you need to download and compile it to use. Its source code is here: SwingWorker.java SwingWorker class Introduction The SwingWorker class can be easily and conveniently used to calculate a value in a new thread. To use this class, you only have a SwingWorker subclass and overwrite the SwingWorker.Construct () method to perform the calculation. Then you instant it and call the start () method on this new instance. For example, a thread is generated in the following code snippet, which constructs a string. Then, the get () method is used to obtain the value returned by the construct method before, and will wait in the case. Finally, the value of the string is displayed on the display. Swingworker worker = new swingworker () {transn "Hello" "" "world";}}; worker.start (); system.out.println ("forker.get (). Tostring () ); In actual applications, constructRuct methods will do more useful (but may take time). For example, it may do one of the following work:

Perform a large number of operations can result in a large number of classes that are loaded for the network or disk I / O block, waiting for other resources in the above code snippet, the characteristics of a SwingWorker class not displayed in the code snippet, when construct () returns, SwingWorker can Let you execute some code in the event distribution process. You can do this by overlying the Finished () method of SwingWorker. Typically, you can use Finished () to display some components that have just been constructed or set data displayed on the component. One limitation of the original version of the SwingWorker class is that once a Worker thread starts running, you can't interrupt it. (Translation: This article, the examples of this article and the SwingWorker class have been updated. No matter how to say, for a interactive application, let users wait until the work thread is complete. If the user wants to terminate an operation being executed, the thread that performs this should be aborted as soon as possible. An interrupt () method is added to the second edition of the SwingWorker class using an Interrupt () method to allow interrupt a thread. Your thread should be interrupted by one of two ways: a thread, such as a Sleep () or wait () method is being execrupting an InterruptedException when Interrupt () is called. The thread can explicitly ask if it has been interrupted, by shaping the following code: thread.interrupted () Using the Sleep () or WAIT () method (such as thread in the later example) generally does not need to be displayed Interrupt. It is usually made to throw an instalRuptedException in the SLEEP () or wait () method. However, if you want to interrupt SwingWorker that does not contain timed cycles, you still need to explicitly check the interrupt with an interrupted () method. An example of an example of introducing a Worker thread discusses a program that contains two Worker threads. The picture below is a screenshot of the master window, and a dialog that it pops up: The source code of the example consists of the following files:

SwingWorker.java threadsexample.java example1.java example2.java You can download a zip file that contains all files above. In this zip file, there is also an example of an explanatory in the HTML format, and the example of this version can explain the problem (but more complicated). Before running this example: /usr/local/java/jdk1.3.0/bin/javac threadsexample.java Run this example with the following command line: /usr/local/java/jdk1.3.0/bin/java threadsexample when you Press the "START" button and the corresponding example of the Worker thread will be created. You can view its progress in your schedule. You can press the "CANCEL" button to interrupt the Worker thread. At the startup example, you will see a dialog prompt you to confirm if it is executed. Let us later in detail later. Example 1: Interrupt Swing Worker thread Next, the example we want to discuss is example1.java. The Worker thread in this example contains a loop that performs 100 times and sleeps half a second between the two cycles. // ProgressBar Maximum Is Numloops (100) ProgressBar's maximum value is Numloops (100) for (int i = 0; i

worker = new SwingWorker () {public Object construct () {return doWork ();} public void finished () {startButton.setEnabled (true); interruptButton.setEnabled (false); statusField.setText (get () toString (). );}}; Finished () method returns after the construct () method (that is, after the Worker thread is complete). Its task is just simply replacing the "start" button, and the "Cancel" button is invalid and set the value displayed by the status domain to the calculation result of the Worker. Remember that the finished () method is to execute in the event dispatch, so it can safely update the GUI directly. Example 2: From the Worker thread prompting the user This example is implemented as the subclass of Example1. The only difference is that after the Worker thread is executed for approximately two seconds, it will block until the user responds to a Continue / Cancel Modal dialog box. If the user chooses not "Continue", we will withdraw from the DOWORK () loop. This example demonstrates a customary method in many Worker threads: If you reach an undesired state in Worker execution, it will block up until the user is reminded or collects more information from the user with a modal dialog box. This approach is a bit complex because the display of the dialog needs to be placed in the event dispatch, and the Worker thread needs to be blocked until the user releases the mode dialog. We use Swingutilities's InvokeAit () method to pop up dialog boxes in the event dispatch. Different from invokelater (), invokeAndWait () will block it until its Runnable object returns. In our example, the runnable object is not returned until the dialog is released. We created an internal Runnable class DoshowDialog to complete the pop-up dialog. An instance variable DoShowDialog.proceedConfirmed, are used to record the user's choice: class DoShowDialog implements Runnable {boolean proceedConfirmed; public void run () {Object [] options = { "Continue", "Cancel"}; int n = JOptionPane.showOptionDialog (Example2.this, "? Example2: Continue", "Example2", JOptionPane.YES_NO_OPTION, OptionPane.QUESTION_MESSAGE, null, options, "Continue"); proceedConfirmed = (n == JOptionPane.YES_OPTION);}} because for showConfirmDialog () Methods A modal dialog is popped, and the call will block until the user releases the dialog.

转载请注明原文地址:https://www.9cbs.com/read-14367.html

New Post(0)