Small thread example -- control output, thread example --

Source: Internet
Author: User

Small thread example -- control output, thread example --
Small thread example -- control output

Function: A small form with two buttons. Click start to start printing on the console. Click Stop to stop printing on the console.

Import java. awt. container; import java. awt. flowLayout; import java. awt. event. actionEvent; import java. awt. event. actionListener; import javax. swing. JButton; import javax. swing. JFrame; public class ThreadDemo extends JFrame {String info = ""; static Thread tstart; Boolean iscontinue = true; // control start or end public ThreadDemo () {super (); container c = getContentPane (); setBounds (300,200,250,100); c. setLayout (new FlowLayout (); JButton jb1 = new JButton ("START"); JButton jb2 = new JButton ("stop"); c. add (jb1); c. add (jb2); jb1.addActionListener (new ActionListener () {// listener event of the Start button @ Override public void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stub tstart = new Thread (new Runnable () {@ Override public void run () {// TODO Auto-generated method stub iscontinue = true; while (true) {if (iscontinue = false) {break;} try {Thread. sleep (1000);} catch (InterruptedException e) {// TODO Auto-generated catch block e. printStackTrace ();} System. out. println (info) ;}}); tstart. start () ;}}); jb2.addActionListener (new ActionListener () {// listener event of the end button @ Override public void actionreceivmed (ActionEvent e) {// TODO Auto-generated method stub iscontinue = false; tstart = null ;}}); setVisible (true) ;}public static void main (String [] args) {new ThreadDemo ();}}

Idea: Create a thread in the Start button, set the control variable iscontinue to true, set the control variable iscontinue to false in the end button, and set the thread to null.

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.