Thread security selection in Java Development and swing

Source: Internet
Author: User

Swing APIs are designed to be powerful, flexible, and easy to use. In particular, we want programmers to easily create new swing components, whether from scratch or by extending some of the components we provide.
  
For this purpose, swing components are not required to support multi-threaded access. Instead, we send a request to the component and execute the request in a single thread.
  
This article discusses threads and swing components. The purpose is not only to help you use the swing API in a thread-safe way, but also to explain why we chose the current thread solution.
  
This article includes the following content:
Single-threaded rule: A swing thread can only be accessed by one thread at a time. Generally, this thread is the event-dispatching thread ).
  
Rule exceptions: Some Operations ensure thread safety.
  
Event distribution: If you need to access the UI from a location other than event-handling or drawing code, you can use the invokelater () or invokeandwait () method of the swingutilities class.
  
Thread creation: If you need to create a thread-for example, to process jobs that consume a lot of computing power or are limited by I/O capabilities-you can use a thread tool class such as swingworker or timer.
  
Why do we implement swing like this: we will end this article with some background information about swing thread security.
  
Swing rules:
  
Once the swing component is implemented (realized), all code that may affect or depend on the component status should be executed in the event dispatching thread.
  
This rule may sound a little scary, but for many simple programs, you don't have to worry about thread issues. Before learning how to write swing code, Let's define two terms: the realized and the event-dispatching thread ).
  
It indicates that the formed paint () method has or may be called. A swing component that acts as a top-level window will be implemented when the following methods are called: setvisible (true), show (), or (possibly surprising) Pack (). When a window is active, all components contained in it are active. Another method to make a component available is to put it into a container that has already been made available. Later, you will see some examples of current components.
  
The event dispatching thread is the thread that executes plotting and event processing. For example, the paint () and actionreceivmed () methods are automatically executed in the event dispatching thread. Another way to put code in the event dispatch thread is to use the invokelater () method of the swingutilities class.
  
All codes that may affect an existing swing component must be executed in the event dispatching thread. However, this rule has some exceptions:
  
Some methods are thread-safe: In the swing API documentation, the thread-safe method is marked with the following text:
  
This method is thread safe, although most swing methods are not.
(This method is thread-safe, although most swing methods are not .)
  
The GUI of an application can often be built and displayed in the main thread: The following typical code is secure, as long as no (swing or other) components are available:
  
Public class myapplication
{
Public static void main (string [] ARGs)
{
Jframe F = new jframe ("labels"); // set each component
// Add to the main framework ......
F. Pack ();
F. Show ();
// Do not do any GUI work ......
}
}
  
All the code shown above is run in the "Main" thread. The call to F. Pack () makes all components below jframe active. This means that F. Show () calls are insecure and should be executed in the event dispatching thread. Even so, as long as the program does not have a visible GUI, it is almost impossible for a jframe or its components to receive a paint () call before F. Show () returns. Because in F. after show () is called, no GUI code is available, so all gui work is transferred from the main thread to the event dispatching thread. Therefore, the Code discussed above is actually thread-safe.
  
The GUI of an applet can be constructed and displayed in the init () method: existing browsers do not draw it before the init () and start () Methods of an applet are called. Therefore, it is safe to construct the GUI in the init () method of an applet, as long as you do not call the show () or setvisible (true) method for the objects in the applet.
  
By the way, if the applet uses the swing component, it must be implemented as a subclass of japplet. In addition, the component should be added to the japplet content pane (content pane), rather than directly added to the japplet. For any applet, you should not perform time-consuming initialization operations in the init () or start () method; instead, you should start a thread to execute time-consuming tasks.
  
The following jcomponent methods are secure and can be called from any thread: repaint (), revalidate (), and invalidate (). The repaint () and revalidate () Methods queue requests for the event dispatching thread, and call the paint () and validate () methods respectively. The invalidate () method only marks a component and all its direct ancestor when it needs to be confirmed.
  
The listener list can be modified by any thread: it is always safe to call the addlistenertypelistener () and removelistenertypelistener () methods. Adding or deleting a listener list does not affect the event distribution in progress.
  
Note: The important difference between revalidate () and the old validate () method is that revalidate () caches the request and combines it into a validate () call. This is similar to the repaint () cache and the Combined Drawing request.
  
Most of the initialized GUI work occurs naturally in the event dispatch thread. Once the GUI becomes visible, most programs are event-driven, such as button actions or mouse clicks, which are always processed in the event dispatching thread.
  
However, some programs always need to execute some non-event-driven GUI work after the GUI becomes visible. For example:
  
A program that requires long initialization before it becomes available: such programs should usually display the GUI during initialization, and then update or change the GUI. The initialization process should not be performed in the event dispatching thread; otherwise, the re-painting component and event dispatching will stop. However, after initialization, the GUI update/change should still be performed in the event dispatching thread on the grounds that the thread is secure.
  
Programs that must respond to non-AWT events to update the GUI: for example, imagine a server program to get requests from programs that may run on other machines. These requests may arrive at any time and cause method calls to the server in some potentially unknown threads. How can I update the GUI by calling this method? Execute the GUI update code in the event dispatching thread.
  
The swingutilities class provides two methods to help you execute code in the event dispatch thread:
  
Invokelater (): Certain code must be executed in the event dispatching thread. This method returns immediately without waiting for the code to be executed.
  
Invokeandwait (): The behavior is similar to invokelater (), except that this method will wait for the code to be executed. Generally, you can use invokelater () to replace this method.
  
The following are examples of using these Apis. See "bingo example" in the Java tutorial, especially the following classes: cardwindow, controlpane, player, and overallstatuspane.
  
  
Use the invokelater () method
  
You can call the invokelater () method from any thread to request the event dispatching thread to run specific code. You must put the code to be run in the run () method of a runnable object and set this runnable object to the invokelater () parameter. The invokelater () method returns immediately without waiting for the event dispatching thread to execute the specified code. This is an example using the invokelater () method:
  
Runnable doworkrunnable = new runnable ()
{
Public void run ()
{
Dowork ();
}
};
Swingutilities. invokelater (doworkrunnable );
  
Use the invokeandwait () method
  
The invokeandwait () method is similar to the invokelater () method, except that the invokeandwait () method will be returned only when the event dispatching thread executes the specified code. If possible, use invokelater () instead of invokeandwait (). If you really want to use invokeandwait (), make sure that the thread that calls invokeandwait () does not hold any locks that other threads may need during the call.
This is an example of using invokeandwait:
  
Void showhellotheredialog () throws exception
{
Runnable showmodaldialog = new runnable ()
{
Public void run ()
{
Joptionpane. showmessagedialog (mymainframe, "Hello there ");
}
};
Swingutilities. invokeandwait (showmodaldialog );
}
  
Similarly, assume that a thread needs to access the GUI status, such as the content of a text field, and its code may be similar to the following:
  
Void printtextfield ()
Throws exception {
Final string [] mystrings = new string [2];
Runnable gettextfieldtext = new runnable (){
Public void run (){
Mystrings [0] = textfield0.gettext ();
Mystrings [1] = textfield1.gettext ();
}
};
Swingutilities. invokeandwait (gettextfieldtext );
System. Out. println (mystrings [0] + "" + mystrings [1]);}
  
If you can avoid using threads, it is best to do so. The thread may be difficult to use and make debugging of the program more difficult. Generally, threads are unnecessary for GUI work in a strict sense, such as updating component attributes.

96 stack Software Programming Network, http://www.96dz.com, recommended c ++ video tutorial, C # video tutorial, Java video tutorial download, Linux programming and web programming learning materials video tutorial download.

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.