An additional part of the Java multi-thread Development Series: Event dispatching thread --- EventDispatchThread,

Source: Internet
Author: User

An additional part of the Java multi-thread Development Series: Event dispatching thread --- EventDispatchThread,

The event dispatching thread is an important knowledge point in java Swing development. It is also very important in Android app development. Today we are interspersed with this thread in multi-threaded development. Learn the event dispatch thread from three aspects: thread reason, principle, and usage.

 

I. Past and present of the event dispatching thread

The Event Dispatch Thread is abbreviated as EDT, which is short for each initials. In some books or blogs, it is also translated into event distribution threads and event scheduling threads. All in all, you just need to know these names. I think the translation here is more accurate.

Those familiar with Swing and awt programming should be familiar with the event dispatch thread. If you disagree, it only means that you are not familiar with Swing and awt programming.

The background of the birth of the event dispatching thread is as follows:

Each control object on the interface has its own data variables. Multi-threaded operations may cause many problems, such as dirty data, out-of-bounds arrays, and empty references.

Li (example)

 

 

Thread A finds that there is data in the panel to be displayed (check data), so it calls the scroll bar to scroll down. In this case, the panel calls the data displayed in the data for display. However, a thread is switched during the presentation process. The data to be displayed is deleted by other thread B, and thread A is awakened again to continue running. The following content is displayed. Because the Check Data logic has passed. Therefore, we need to call data that does not exist for display. At last there will be various strange problems. (If you do not understand it, it is understood that each thread is ultimately operating on the data source of the control, the control may be displayed with an exception ).

Generally, the solution to this multi-threaded ice method is "Lock" or "synchronization ".

At that time, Sun's Swing team initially thought this way, but the Swing team eventually changed its mind for the following two reasons:

1. Data Synchronization is time-consuming while ensuring thread security. The most important thing about the UI is the interface response speed. After all, no one wants to operate on a slide.

2. Swing team investigated other groups in the thread-safe user interface toolkit side (anti-theft connection: This article first from the http://www.cnblogs.com/jilodream/) experience, found that the results are not so good: the engineer who develops the thread security package is dizzy by various synchronization operations, and the program is often deadlocked.

In this regard, the Swing team decided to use a single thread to control the control painting of the entire interface. This thread is the event dispatching thread.

The event dispatch thread is created as follows:

 

Ii. Principles of event dispatching threads

The principle of event dispatching thread is actually very simple. In the interface Background, only this thread is working, and this thread is the event dispatching thread. When you need to perform operations on the interface, add these actions to the event queue of the event dispatching thread. The event dispatching thread will execute the requests in this queue in sequence.

This is a bit like a single-core cpu multi-thread operation scenario. The difference is that at this time, the function of the event dispatching thread is single-core cpu.

You can view the specific content (the image is from the network)

 

Each thread queues GUI requests, and then the event dispatching thread executes the requests in this queue in sequence.

From the perspective of the design model, this is a typical "consumer" model. If you are interested, you can refer to the relevant design model content.

After learning about the principle of the event dispatching thread, we will find this problem:

Events in eventQueue are not prioritized and follow the FIFO principle. If the request at the front side is very time-consuming and requires a large number of db requests, IO operations, and other operations, the subsequent requests can only wait.

At the beginning, we abandoned 'sync' for fast purposes. Now the interface is stuck, which violates the original intention.

Based on the above, Swing developers proposed two principles to be observed when using event distribution threads:

1. Only the event dispatching thread can call the Swing component. Other threads are far away from the component. (In some cases, this rule is called single-thread rule)

2. If a GUI request is time-consuming, do not send the request to the event dispatching thread. After the request is processed by another thread, a few interface requests are sent to the event dispatching thread.

 

3. How to Use the event dispatch thread

I have mentioned a lot above, but I don't know how to use the event dispatching thread, so it is useless as described above.

First, we mentioned that the event dispatching thread is a thread automatically started by the system after the GUI is started (in fact, there is still an initialization thread that starts the GUI for a short time.

Therefore, we do not need to manually create and run threads. What we need to do (anti-theft connection: This article first from the http://www.cnblogs.com/jilodream/) is to add various GUI requests to the event dispatch thread to eventQUEUE.

 

Swing provides three common APIs

1 SwingUtilities. invokeAndWait (Runnable runnable) // for Synchronous requests, the request sending thread will continue to execute the remaining code until EDT executes its own request; 2 3 SwingUtilities. invokeLater (Runnable runnable) // for asynchronous requests, the request sending thread will execute the remaining code after the request is added to the eventQUEUE of EDT; 4 5 SwingUtilities. isEventDispatchThread () // determines whether the current thread is an event dispatching thread.

Generally, when writing the request code, it is best to first determine whether the execution thread distributes the thread for the event, and then select whether to directly execute or add it to the event queue.

It is worth noting that there is a problem here:

That is, if the current thread is the event dispatching thread, it is not allowed to execute the invokeAndWait () synchronization method.

This is because, in this case, EDT will pause (wait) at this point, wait for EDT to execute the add request, and because EDT has paused at this point, therefore, EDT will not process requests in eventQUEUE, forming a deadlock.

Fortunately, JDK has already verified this situation, so those who are not familiar with the above do not need to care too much, as long as you remember the results:

 

 

Finally, let's look at an example of code in actual work.

 1 if(SwingUtilities.isEventDispatchThread()) 2 { 3     OptTree.RefreshNode(); 4 } 5 else 6 { 7     SwingUtilities.invokeAndWait(new Runnable() 8     { 9         @Override10         public void run()11         {12             OptTree.RefreshNode();13         }14     });15 }


 

 

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.