线程小例子--控制输出
线程小例子--控制输出
功能:一个小窗体,两个按钮,点击开始按钮,控制台开始打印,点击停止按钮,控制台停止打印。
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; //控制开始还是结束 public ThreadDemo(){ super(); Container c=getContentPane(); setBounds(300,200,250,100); c.setLayout(new FlowLayout()); JButton jb1=new JButton("开始"); JButton jb2=new JButton("停止"); c.add(jb1); c.add(jb2); jb1.addActionListener(new ActionListener() { //开始按钮的监听事件 @Override public void actionPerformed(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() { //结束按钮的监听事件 @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub iscontinue=false; tstart=null; } }); setVisible(true); } public static void main(String[] args){ new ThreadDemo(); } }
思路:在开始按钮中新建线程,将控制变量iscontinue置为true,在结束按钮中将控制变量iscontinue置为false,同时将线程置为null
务实,说实话!