Swing multithreaded Programming __ programming

Source: Internet
Author: User
Tags event listener
Key Words:Swing, multi-threading, Gui,swingworker Summary:This paper discusses how to develop a multithreaded swing program to improve the response speed and performance of swing programs. In the near future, I'm going to launch a series of articles that study swing programs, which is to salute the designers of swing, the great GUI library. Swing This excellent GUI library has been unable to occupy the desktop market, it is puzzling, today, I use my efforts, for Java in the desktop market success to do my meager power. single-thread development mechanism of swingMultithreaded development is obviously more fun, efficient, and much more enjoyable than single-threaded development. This is especially true in Java, a language that naturally supports multithreading. However, the most important component of the Java Swing is a single thread. Swing is not the only single thread, and most GUI libraries are single-threaded. Because, in the event processing of the GUI, the events and the underlying resources of handling events are so complex that it is difficult to avoid deadlocks and resource competition problems by using multithreaded development. Furthermore, if too many system resources are locked, the systematic performance of the GUI will have a negative impact. As a result, swing has been developed into a single-threaded programming model based on event queues. The events on the GUI are executed sequentially on the "event-distributing thread", and there is no contention for resources on the event. Java.awt.EventQueue class, you perform this function. EventQueue is a platform-independent class that queues events from the underlying same-body class and trusted application classes. It encapsulates the asynchronous event assignment mechanism, which extracts events from the queue and then assigns these events (events as parameters) by calling the Dispatchevent (awtevent) method on this eventqueue. The special behavior of the mechanism is related to the implementation. The only requirement for assigning events that are actually queued (note that the events being sent to EventQueue can be merged) are: in order. That is, you are not allowed to assign multiple events from the queue at the same time. The order of assignment is the same as the order in which they are queued. In other words, if awtevent A is first queued to EventQueue, then event B cannot be assigned before event a. AWTEvent b. Some browsers divide applets in different base code into separate contexts and create a wall between these contexts. In such a scenario, each context will have a eventqueue. Other browsers put all applets into the same context, which means that all applets have only one global eventqueue. The behavior is related to the implementation. For more information, refer to your browser's documentation. The processing of all SWING/AWT events is performed in the unique "event-issuing thread". In general, we use the 2 methods of the EventQueue class to execute the event-handling method in the event-distributing thread. Invokelater
public static void Invokelater(Runnable Runnable)
Causes the runnable run method to be invoked on the EventQueue assigned thread. Occurs after all pending events have been processed. Parameters:Runnable-runnable, the Run method should be executed synchronously on EventQueue start with the following version:1.2 See also:Invokeandwait (java.lang.Runnable) invokeandwait
public static void invokeandwait(Runnable Runnable)
Throws Interruptedexception,
InvocationTargetException
Causes the runnable run method to be invoked on the EventQueue assigned thread. Occurs after all pending events have been processed. The call is blocked before this occurs. If called from an event assignment thread, the method throws an Error. Parameters:Runnable-runnable, the Run method should be executed synchronously on EventQueue Thrown:Interruptedexception-If another thread has interrupted the thread invocationtargetexception-if the runnable is running, throw a throwable start with the following version:1.2 See also:The Invokelater (java.lang.Runnable) design of Swing's UI components is typically run on the event-distributing thread. issues caused by swing single-threaded developmentJava is a multithreaded programming language. Multithreading brings concurrency benefits to programs. One problem with swing single-threaded development is that if too many operations are performed on an "event-issuing thread", the GUI interface stops and the system responds and operates very slowly. Since the "event-distributing thread" is designed to handle GUI events, we should only implement the GUI event-related code in the event-issuing thread. Other interface-independent code should be executed in other Java threads. In this way, we still use Swing's single-threaded programming model in swing event handling, while other business operations use the multithreaded programming model, which can greatly improve the response and speed of swing programs, and fully utilize the advantages of Java multithreaded programming. the threads of the swing programThere are two kinds of threads for swing applications, one is "event-distributing thread", in fact there is only one thread, and the other is a generic Java thread that can have countless threads. Code related to system event handling needs to be run in the event distribution thread. is typically the UI component of swing. Swing components, which include the Swingui component, often need to run in the event-distributing thread. Business-related code, especially large amounts of computing, or the time-consuming operations involving IO, the network, waiting for resources, need to be placed in a separate Java thread to achieve parallel operations and improve performance. Swing Program Threading Application ExampleBelow, I take a general swing program as an example to illustrate how swing multithreaded programming should be done. 1,jframe Subclass: public class Diagramdesignerjframe extends Javax.swing.JFrame {...} This is a subclass of JFrame, a top-level window. The top-level window is a window that gets from the operating system.   Java can use the brushes from the operating system in this window to draw the GUI that swing needs. 2,main Method:/** * @paramargs * The command line arguments * * publicstaticvoidMain (String args[]) {/** * in a generic thread, execute the initialization of the spring container. Try{Springutil.getctx (); } Catch(Beansexception e)         {* * */e.printstacktrace (); } Catch(Documentexception e)         {* * */e.printstacktrace (); } java.awt.EventQueue.invokeLater ( NewRunnable () { publicvoidRun () { NewDiagramdesignerjframe (). setvisible ( true);     }         }); First, we execute the initialization of the spring container in a generic Java thread. This is a very large number of computations and has nothing to do with operating system events. We then asynchronously perform instantiation and visualization of JFrame subclasses in the event-distributing thread. NewDiagramdesignerjframe () This instantiation operation is performed in an "event-distributing thread"; setvisible ( trueis also performed in the event-distributing thread. Application of multi-threading in controllerSwing is an example of MVC pattern design. Its controller, is the event listener, generally implemented as an internal class. The various components of swing can register a very wide range of event listeners, namely "Controller". The UI component of swing is its interface view. The model of each swing component is its models. Typically, users perform actions on swing UI components, fire events, and then process the controller to modify the model of swing components. Model also fires Java events (not operating system events) so that the UI is redrawn based on the new model value. We call the business code in the controller, which can be time-consuming. After the call is over, the swing component's methods are often invoked to update the appearance of the swing application. Therefore, we should put the code that invokes the business method in the swing controller to a new generic Java thread to execute.     After the execution completes, execute the Swing component update code in the event distribution thread. The following is the controller that performs the Save As feature. It first saves the data in the swing component and then opens the file to select its dialog box, allowing the user to choose which file to save to. /**       * @returnSaveasactionlistener * PublicActionListener Getsaveasactionlistener () { if( This. Saveasactionlistener = = NULL) { This. Saveasactionlistener = NewActionListener () {/** * response to click the Save As button for the event method * * publicvoidactionperformed (ActionEvent e) { FinalSwingWorker worker = NewSwingWorker () {@Override PublicObject construct () {/* * * * * Try{getJEditorPane1 (). Firecontrollerchangelistener (); returnDiagramdesignerjframe.                         servicefinished; } Catch   (Documentexception E1) {                             /*                                *                               */                              E1.printstacktrace ();                              Joptionpane.showmessagedialog (                                      Diagramdesignerjframe. This, "Your input does not conform to the XML format requirements."                         "+ e1.getmessage ()); } Catch   (Exception E1) {                             /*                                *                               */                              E1.printstacktrace ();                         }                               Returnnull;                           /** * Executes the constructor asynchronously on the GUI after it finishes execution. */ publicvoid  finished () {                              saveaction ();                             }                                              };                      Worker.start ();                                                                               }               };          }            returnSaveasactionlistener; } SwingWorker This swing multithreaded development helper classThe above example uses the SwingWorker, a swing multithreaded development helper class. In JDK6, this class is already part of swing. Here, I'm using JDK5, so I was using the SwingWorker class that Sun created before. which PublicObject construct () {...} code in this method, running in a new generic Java thread. We put the time-consuming business approach into this approach. publicvoidFinished () {

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.