线程停止方法
- 自然停止
- 标志位法,外部设置一个标志位控制
- 不要使用stop、destroy被废弃的方法
public class StopThread {
public static void main(String[] args) {
new Thread(new TestThread()).start();//启动线程
}
}
class TestThread implements Runnable{
private static boolean stop=false;//设置标志位
private Date now=new Date();//定义一个时间类
private int i=0;//定义计数器
@Override
public void run() {
while (!stop){//通过标志位停止的循环
if(i==10){//判断计时器
setStop();//执行停止方法
System.out.print("Stop:");//输出语句
now= new Date(System.currentTimeMillis());//刷新时间
System.out.println(new SimpleDateFormat("HH:mm:ss").format(now));//打印当前时间
}else{
System.out.print("Now:");//输出语句
now= new Date(System.currentTimeMillis());//刷新时间
System.out.println(new SimpleDateFormat("HH:mm:ss").format(now));//打印当前时间
}
try {
Thread.sleep(1000);//等待一秒
i++;//计数器+1
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void setStop(){//停止方法
this.stop=true;//标志位反转
}
}