Multi-threaded implementation of responsive interface (Java)

Source: Internet
Author: User

"One of the most important uses of multithreading is to build a" responsive "interface.

--excerpt from the Java programming idea

To understand this, we can assume a scenario where a program is used to handle a large number of mathematical operations, which in most cases consumes a lot of CPU time.

In the process of processing the data and try to interact with the user, and if there is only one main thread in the process, then each time the program needs to wait until the main thread of the task is completed

In order to respond to interface operations, which is not acceptable in the usual circumstances. We can imagine a scenario in which a program is running, and if suddenly something needs to go away (tutor please

Go out to eat, the opportunity is rare), then you may need to click the Close button, close the program, but the program said I have 200 cycles to run, no time to you, wait for me. If you encounter this

Situation, we also have the means to open the Task Manager, end the process, simple and effective but very violent.

Next we will give two examples, one is a single-threaded response to the interface of the example, one is multi-threaded (double-threaded) to the interface flexible example.

The program interface is, the approximate process is when we click the Start button, the program starts from 0 to increment the count, and the results are displayed in the input box, and when we click the toggle button, the count is paused,

Click Count again to restore.

To demonstrate the difference between single-threaded and multithreaded, we define this counting process as a dead loop, from 0 to infinity, while the toggle button can be used to pause the loop. In the example one

There is only one main thread, which causes the program to not be able to close the button when the Count loop is in progress, and we cannot dismiss the window. In order to solve this problem, in the example two we put this count

Process into a separate thread, and the main thread is specifically designed to respond to the interface, and the program can run normally.

  

(1) Example 1

  
 PackageHongqi.daiwei.lianyuan.java.multithread;ImportJava.applet.Applet;Importjava.awt.BorderLayout;ImportJava.awt.Button;ImportJava.awt.Frame;ImportJava.awt.TextField;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJava.awt.event.WindowAdapter;Importjava.awt.event.WindowEvent; Public classCounter1extendsApplet {Private intCount = 0; PrivateButton ONOFF =NewButton ("Toggle"); PrivateButton start =NewButton ("Start"); PrivateTextField T =NewTextField (10); Private BooleanRunflag =true;  Public voidinit () {Add (t); Start.addactionlistener (NewStartl ());        Add (start); Onoff.addactionlistener (NewONOFFL ());        Add (ONOFF); Super. Init (); }         Public voidGo () { while(true){            Try{thread.currentthread (); Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }            if(Runflag) {T.settext (integer.tostring (Count++)); }        }    }        classStartlImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {go (); }    }        classOnofflImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {Runflag= !Runflag; }    }         Public Static voidMainintargv, String argc[][]) {Counter1 applet=NewCounter1 (); Frame Aframe=NewFrame ("Counter1");        Aframe.add (applet, borderlayout.center); Aframe.setsize (300, 200);        Applet.init ();        Applet.start (); Aframe.setvisible (true); Aframe.addwindowlistener (NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);            }                    }); }}
View Code

(2) Example 2

Thread class:

 PackageHongqi.daiwei.lianyuan.java.multithread; Public classSeparatesubtaskextendsThread {Counter2 C=NULL; Private BooleanFlag =true; Private intCount = 0;  PublicSeparatesubtask (Counter2 c) { This. C =C;  This. Start (); }         Public voidInvertflag () {flag= !Flag; }         Public voidrun () { while(true){            Try{sleep (100); } Catch(interruptedexception e) {e.printstacktrace (); }            if(flag) {C.t.settext (integer.tostring (Count++)); }        }    }    }
View Code

Main class:

 PackageHongqi.daiwei.lianyuan.java.multithread;ImportJava.applet.Applet;Importjava.awt.BorderLayout;ImportJava.awt.Button;ImportJava.awt.Frame;ImportJava.awt.TextField;Importjava.awt.event.ActionEvent;ImportJava.awt.event.ActionListener;ImportJava.awt.event.WindowAdapter;Importjava.awt.event.WindowEvent; Public classCounter1extendsApplet {Private intCount = 0; PrivateButton ONOFF =NewButton ("Toggle"); PrivateButton start =NewButton ("Start"); PrivateTextField T =NewTextField (10); Private BooleanRunflag =true;  Public voidinit () {Add (t); Start.addactionlistener (NewStartl ());        Add (start); Onoff.addactionlistener (NewONOFFL ());        Add (ONOFF); Super. Init (); }         Public voidGo () { while(true){            Try{thread.currentthread (); Thread.Sleep (1000); } Catch(interruptedexception e) {e.printstacktrace (); }            if(Runflag) {T.settext (integer.tostring (Count++)); }        }    }        classStartlImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {go (); }    }        classOnofflImplementsactionlistener{ Public voidactionperformed (ActionEvent e) {Runflag= !Runflag; }    }         Public Static voidMainintargv, String argc[][]) {Counter1 applet=NewCounter1 (); Frame Aframe=NewFrame ("Counter1");        Aframe.add (applet, borderlayout.center); Aframe.setsize (300, 200);        Applet.init ();        Applet.start (); Aframe.setvisible (true); Aframe.addwindowlistener (NewWindowadapter () { Public voidwindowclosing (windowevent e) {system.exit (0);            }                    }); }}
View Code

  

Multi-threaded implementation of responsive interface (Java)

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.