Responsive user Interface

Source: Internet
Author: User
Tags sleep thread thread class

As our starting point, consider a program that needs to perform some CPU-intensive calculations. Because the CPU "wholeheartedly" for those computing services, so the user's input is very slow, almost no response. Here, we use a composite applet/application (program/application) to simply display the result of a counter:
 

: Counter1.java//A non-responsive user interface package C14;
Import java.awt.*;
Import java.awt.event.*;

Import java.applet.*;
  public class Counter1 extends Applet {private int count = 0;
  Private button onoff = New button ("Toggle"), start = New button ("Start");
  Private TextField t = new TextField (10);
  Private Boolean runflag = true;
    public void Init () {Add (t);
    Start.addactionlistener (New Startl ());
    Add (start);
    Onoff.addactionlistener (New Onoffl ());
  Add (OnOff);
      public void Go () {while (true) {try {thread.currentthread ()]. Sleep (100);
    catch (Interruptedexception e) {} if (Runflag) T.settext (integer.tostring (count++));
    Class Startl implements ActionListener {public void actionperformed (ActionEvent e) {go (); } class Onoffl implements ActionListener {public void actionperformed (ActionEvent e) {runflag =!runflag
    ; }} public static void Main (StriNg[] args) {Counter1 applet = new Counter1 ();
    Frame aframe = new Frame ("Counter1"); Aframe.addwindowlistener (New Windowadapter () {public void windowclosing (WindowEvent e) {System.
        Exit (0);
    }
      });
    Aframe.add (applet, borderlayout.center);
    Aframe.setsize (300,200);
    Applet.init ();
    Applet.start ();
  Aframe.setvisible (TRUE); }
} ///:~

In this program, AWT and the code of the program should be familiar to everyone, the 13th chapter has a very detailed account of this. The Go () method is what the program does wholeheartedly: Place the current count (count) value into the TextField (text field) T, and then add the value to count.
Part of the Infinite loop within go () is call Sleep (). Sleep () must be associated with a thread (thread) object, and it seems that every application has some thread associated with it (in fact, Java itself is built on a thread, and there are certain threads that run along with the application we write). So whether or not we explicitly use a thread, we can use Thread.CurrentThread () to produce the current thread that is used by the program, and then call Sleep () for that thread. Note that Thread.CurrentThread () is a static method of the Thread class.
Note that sleep () may "throw" a interruptexception (interrupt violation)-although such an offence is considered a "malicious" means of aborting a thread and should be eliminated as much as possible. Again, we are reminded that the offence is caused by exceptional circumstances and not for the normal flow of control. This includes an interruption to a "sleep" thread to support a language feature for the future.
Once the Start button is pressed, go () is called. If you look at Go (), you may naturally (as I do) think it should support multithreading because it goes into "sleep" state. That is, even though the method itself is "asleep", the CPU should still be busy monitoring other button "press" events. But there is a problem, that is, go () is never returned, because it is designed to be an infinite loop. This means that actionperformed () does not return at all. Because you're stuck in actionperformed () after the first key, the program can't control any other events (if you want to, you have to "kill" the process in some way-the easiest way is to press CTRL + C in the console window).
The basic problem here is that go () needs to continue to perform its own operation, while at the same time it needs to be returned so that actionperformed () can be completed, and the user interface can continue to respond to the user's actions. However, traditional methods such as Object Go () do not return control to other parts of the program while continuing. This sounds like an impossible thing to do, just as the CPU must be in two places at once, but the thread can fix everything. The threading model (and programming support in Java) is a program-authoring specification that can be performed simultaneously in a single program with several operations. Depending on this mechanism, the CPU can allocate a portion of its own time for each thread. Each thread "feels" itself as if it owns the entire CPU, but the CPU's computing time is actually shared among all threads.
The threading mechanism has reduced some computational efficiency, but it has gained great benefit regardless of the design of the program, the balance of resources, or the convenience of user's operation. In a comprehensive consideration, this mechanism is extremely valuable. Of course, if multiple CPUs were installed, the operating system would be able to decide which threads to allocate for different CPUs, and the overall speed of the program would be faster (all of which required the operating system and application support). Multithreading and multitasking are one of the most effective ways to give full play to multiprocessor capabilities.

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.