About SWT UI threads and non-UI threads

Source: Internet
Author: User
Tags gettext message queue

To understand the UI thread, first look at the concept of "message loops". Link is the entry on the Baidu Encyclopedia, in short, the operating system to the user interface to translate each operation into a corresponding message, join the message queue. The message is then forwarded to the corresponding application (typically, the active window), and the application processes the messages according to its own logic. If the application handles a message event for a long time, the subsequent messages cannot be processed in time, causing the application to become unresponsive, often called "suspended animation". So, if an application takes a long time to process an event, it needs to be handled in a separate thread. Let's review the structure of the preceding simple SWT program:
public static void  main (String[] args)  {Display display = new display (); Shell shell = new shell (display); Shell.open (); while (!shell.isdisposed ()) {if (!display.readanddispatch () ) Display.sleep (); } display.dispose (); } 

The while loop is the beginning of processing the message loop, that is, the main thread of an SWT program is the corresponding so-called UI thread.

Where in the program is the UI thread and what is a non-UI thread
    1. The main thread is the UI thread
    2. The Listener method is the UI thread such as the following applet:
Label label =New Label (Shell, SWT.    NONE); Label.settext ("Enter Your Name:"); Text Text =new Text (Shell, SWT.    BORDER); Text.setlayoutdata (new rowdata (100, SWT.default)"); Button OK = new button (shell, Swt. PUSH); Ok.settext ( "OK") Ok.addselectionlistener (new Selectionadapter () {@Override public void widgetselected ( Selectionevent e) {while (true) {System.out.println (1); try {thread.sleep (1000);} catch (interruptedexception E1) {e1.printstacktrace ();}} } }); 

Simulation in the program after clicking the button, a time-consuming operation can be seen, the program is in an unresponsive state:

Avoid non-responsiveness

So, how to avoid the program into a non-responsive state? In fact, it is very simple, do not perform long operations in the UI thread, if necessary to take a time-consuming operation, it is executed in another thread:

Ok.Addselectionlistener (New Selectionadapter () { @Override public void widgetselected (Selectionevent e) {new thread () {public void run () {while (True) { System. Out. println (1); try {thread. Sleep (1000);} catch (Interruptedexception E1) {e1.< Span class= "Hljs-selector-class" >printstacktrace (); }}}}.start (); } }); 

This is done again, and you can see that the program will no longer go into an unresponsive state when the button is clicked.

Non-UI thread access UI

So the operation of the control must be done in the UI thread, otherwise it would throw a thread access error, or in the case of the code above, we now change to print the text of the text control:

Ok.Addselectionlistener (New Selectionadapter () {@Override public void widgetselected (Selectionevent e) {The code here directly in the Listener method is the UI thread new Thread () {public  void run () { //Here is another separate thread, non-UI thread while (true ) {System.  Out.  println (Text.gettext ()); try {Thread.  Sleep (+),} catch (Interruptedexception E1) {E1.  Printstacktrace (); }}}}.start (); } });

To run the program, click the button and the following exception will be thrown:

ExceptionIn thread"Thread-0" ORG.ECLIPSE.SWT.Swtexception: Invalid thread Access at Org.eclipse.swt.SWT.error (SWT.Java:4441) at Org.eclipse.swt.SWT.error (SWT.java:4356) at Org.eclipse.swt.SWT.error (Swt. Java:4327) at Org.eclipse.swt.widgets.Widget.error (widget.< Span class= "hljs-string" >java:476) at Org.eclipse.swt.widgets.Widget.checkWidget (Widget. Java:367) at Org.eclipse.swt.widgets.Text.getText (Text.java:1350) at Test. Snippet108$1$1.run (Snippet108. Java:24)        

The use of the display class's Syncexec (Runnable) or asyncexec (Runnable) Two methods for this kind of access to the UI in a non-UI thread is performed:

Ok.Addselectionlistener (New Selectionadapter () {@Override public void widgetselected (Selectionevent e) {The code here is directly in the listener method, which is the UI threadNewThread () {PublicvoidRun () {//here is another separate thread, non-UI thread while (True) { //non-UI thread access UI display syncexec (new Runnable () { @Override public void run () { //This code will actually be placed in the UI thread to execute System.out. println (Text.gettext ()); } }); try {thread. Sleep (1000);} catch (Interruptedexception E1) {e1.< Span class= "Hljs-selector-class" >printstacktrace (); }}}}.start (); } }); 

Note that the Syncexec (runnable) method parameter Runnable object is actually placed in the UI thread, so be careful not to put tread.sleep () in this runnable, otherwise it will cause the interface to be unresponsive.

The difference between the Syncexec and Asyncexec methods is that one of the two methods will wait for the runnable to finish before returning, and the Asyncexec method is to return immediately, and the UI thread will execute runnable when there is an idle time.

So, is it possible to execute with the Asyncexec method while putting the above sleep in the runnable? The answer is still no, because the runnable is actually going to be executed in the UI thread, and if the runnable is very time consuming, it will also cause the interface to fall into an unresponsive state of 1 seconds at a time, which is equivalent to a new thread executing a time-consuming operation.

About SWT UI threads and non-UI threads

Related Article

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.