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.