Discussion of threads about UI programs in eclipse

Source: Internet
Author: User
Tags join key return thread
Although the threading mechanism between the various operating systems is different, the program is roughly the same. When a user uses a GUI program, the operating system produces a GUI event that determines which window or program accepts each event and puts it in the program's event queue, when the mouse is clicked or the key on the keyboard is pressed.

The underlying structure of any GUI program is an event loop. The program first initializes the event loop, and start the loop, which receives the GUI events sequentially from the event queue and responds accordingly. The program should respond to the incident quickly so that the program always responds to the user, for example, the user points to a button in the program and the program doesn't Should be, then this program should be regarded as a failure of the program it.

If a UI event raises a transaction that takes a long time, then you should put it in a separate thread so that the program's loop of events will be back in response to the user's next action. Threads are a very complex subject, and if handled poorly it can easily lead to deadlocks and other bad situations.

Fortunately, Eclipse has provided us with a convenient UI thread pack to develop plug-ins that greatly simplifies many of the underlying complexities. Take a look at a few simple concepts first.

1.SWT UI Thread

SWT uses a thread pattern that is directly supported by the operating system, and the program runs a time loop in the main program and Chengri the response in this line. Look at this code, the UI thread is the thread that created the display.

public static void Main (String [] args) {
Display display = new display ();
Shell shell = new shell (display);
Shell.open ();
Start Event Loop
When you turn off the window
while (!shell.isdisposed ()) {
if (!display.readanddispatch ())
Display.sleep ();
}
Display.dispose ();
}

In a simple applet, a UI thread can be satisfied. But if it's a long time operation, you'd better not do it with the UI thread, you can give it to the job. It's actually another thread that starts up, which is the non-UI thread that I'm going to say.

2. Job

The job class is provided by the Org.eclipse.core.runtime plug-in. It enables client programmers to easily execute code in another thread. Look at a small example:

Job Job = new Job ("My A-job") {
Protected Istatus Run (Iprogressmonitor monitor) {
System.out.println ("Hello World (Background Job)");
return status.ok_status;
}
};
Job.setpriority (Job.short);
Job.schedule (); Start as soon as possible

The default priority for a job is job.long, where the priority is higher than it is, and as soon as you call Job#schedule (), it runs the code in Run () in another thread as quickly as possible. Let's look at a small example:

Final Job Job = new Job ("Long Running job") {
Protected Istatus Run (Iprogressmonitor monitor) {
try {
while (Hasmoreworktodo ()) {
Do some work
// ...
if (monitor.iscanceled ()) return status.cancel_status;
}
return status.ok_status;
finally {
Schedule (60000); Start again in a hour
}
}
};
Job.addjobchangelistener (New Jobchangeadapter () {
public void Do (Ijobchangeevent event) {
if (Event.getresult (). IsOK ())
PostMessage ("Job completed successfully");
Else
Posterror ("Job did not complete successfully");
}
});
Job.setsystem (TRUE);
Job.schedule (); Start as soon as possible

Monitor is a progress display, it will automatically display when the job is run, if the task is completed successfully, return Status.ok_status, if the user interrupted in the progress display bar, return Status.cancel_ STATUS. Above schedule (60000); it is to let the job automatically run every 1 hours, job again a very powerful function. Then you can add listeners to the job,
Job.setsystem (TRUE); If you call Setuser (true), it is defined as user-level, user-level, and default-level job.

At run time will be reflected in the UI form, if it is a user job, then a progress display window will pop up, allowing users to choose to run in the background, the following figure is a job automatically run the effect:



Again, describe a method that the job often uses job#join (), the system calls to a job, and calls its run () method. Let's look at the following example:

class Trivialjob extends Job {
Public Trivialjob () {
Super ("Trivial Job");
}
Public Istatus Run (Iprogressmonitor monitor) {
System.out.println ("This is a job");
return status.ok_status;
}
}

The creation and schedule of the job are as follows:

trivialjob job = new Trivialjob ();
System.out.println ("About to schedule a job");
Job.schedule ();
System.out.println ("Finished scheduling a job");

Their execution is not related to time, the output may be as follows:

About to schedule a job
This is a job
Finished scheduling a job

It may also be:

About to schedule a job
Finished scheduling a job
This is a job

If you want a job to continue after it has finished running, you can use the join () method and the join () will block until the job runs out.

Example:

trivialjob job = new Trivialjob ();
System.out.println ("About to schedule a job");
Job.schedule ();
Job.join ();
if (Job.getresult (). IsOk ())
System.out.println ("Job Completed with success");
Else
System.out.println ("Job did not complete successfully");

After the above code executes, the output should be like this:

About to schedule a job
This is a job
Job completed with success

Job function is very powerful, there are many features I will introduce later, can also check the official Help document, here first put a few common problems. See:

Http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/runtime_jobs.htm

3. If you add code that changes the UI in the job, it will fail. The reasons are as follows:

If calling UI,SWT in a non-UI thread throws a swtexception, there are several techniques to change the UI in a non-UI thread:

The first type is:

Display#syncexec (Runnable) or
Diaplay#asyncexec (Runnable)

The second type:

Another job that has been developed is uijob, which can run code that changes the UI directly inside it, but it runs in SWT's Asyncexec () method. All classes that inherit uijob should override the Runinuithread method instead of the Run method.

3. With regard to the progress shown

In the JFace:

The Org.eclipse.jface.operations package defines some interfaces that are used to run long tasks under the progress bar. can see:
Http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/jface_operations.htm

In Eclipse plug-in and RCP development:

User-level jobs are the most interoperable, not only to enable users to cancel jobs with the Cancel key, but also to show specific situations in detail, but note:

Detail will only appear in the following two ways:

Iprogressservice#busycursorwhile or
Iprogressservice#runinui

1) Examples of iprogressservice#busycursorwhile usage:

Notice that there is something in the run () that has nothing to do with the UI:

Iprogressservice progressservice = Platformui.getworkbench (). Getprogressservice ();
Progressservice.busycursorwhile (New irunnablewithprogress () {
public void run (Iprogressmonitor monitor) {
Do non-ui work
}
});

Effect:



2) Examples of Iprogressservice#runinui usage:

Note that the run () can do some UI-related things here.

Progressservice.runinui (
Platformui.getworkbench (). Getprogressservice (),
New Irunnablewithprogress () {
public void run (Iprogressmonitor monitor) {
Do UI work
}
},
platform.getworkspace (). Getroot ());

Effect:



The last argument here can be null, or the rule for this operation, where we set the lock on the workbench when we run this UI operation.

More specific can see:

http://help.eclipse.org/help30/index.jsp?topic=/org.eclipse.platform.doc.isv/guide/workbench_jobs.htm

In addition, there are a few times, we do not want to pop a progress bar window, but only at the bottom of the status bar display on it, very simple, write their own job class, in the construction method to add a sentence:SetUser (false); It's OK.



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.