其他分享
首页 > 其他分享> > 线程停止 06

线程停止 06

作者:互联网

线程停止

package Runnable1;
/*
1.建议线程正常停止-->利用次数,不建议死循环
2.建议使用标准志位-->设置一个标志位
3.不要使用stop或者destroy等过时或者jdk不建议使用的方法
*/
public class TestStop implements Runnable
{
   private boolean flag=true;
   public static void main(String[] args)
  {
       TestStop testStop=new TestStop();
       new Thread(testStop,"").start();
       for (int i = 0; i < 100; i++)
      {
           System.out.println("main"+i);
           if (i==900)
               //调用stop方法
               testStop.stop();
           System.out.println("线程该停止了");
      }
  }

   @Override
   public void run()
  {
       if (flag) {
           for (int i = 0; i < 100; i++) {
               System.out.println("run...Thread"+i++);
          }

      }
  }
   //设置一个公开的方法停止线程,转换标记志位
   public void stop()
  {
       this.flag=false;
  }
}

 

                             2. 为线程设置一个布尔标志,定期的检测,标记是否为真。如要停止一个线程,就把标记为true。

package src;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;


public class Clock extends JFrame
{
JPanel p=new JPanel();
JLabel lab=new JLabel();
JButton btn1=new JButton("开始");
JButton btn2=new JButton("暂停");
Date nowtime;
Thread t;
boolean flag;
public Clock()
{
p.add(lab);
p.add(btn1);
p.add(btn2);
btn1.addActionListener(new time());
btn2.addActionListener(new time());
this.setContentPane(p);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(300,100);
this.setResizable(false);
this.setLocationRelativeTo(null);
}
public void gettime()
{
nowtime =new Date();
SimpleDateFormat f=new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒SSS毫秒   EEE");//SimpleDateFormat是一个格式化和解析日期的类
String str=f.format(nowtime.getTime());//获取当前时间并以指定的格式f转化为字符串
lab.setText(str);
}
public static void main(String[] args)
{
Clock fr=new Clock();
fr.gettime();
fr.setVisible(true);
}
class time implements ActionListener
{
public void actionPerformed(ActionEvent e)
{

   if (e.getSource()==btn1)
  {
  flag=true;
  t=new Thread(new thread());
  t.start();
  }
else if (e.getSource()==btn2)
{
flag=false;
}
}
}
class thread implements Runnable
{

@Override
public void run()
{
while (flag)
{
gettime();
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}


}
}
}
 

标签:06,import,void,flag,线程,new,停止,public
来源: https://www.cnblogs.com/zjwcoblogs/p/16515436.html