线程的生命周期

class Threadlife implements Runnable{
 private boolean flag = true; //定义标志位
 public void run(){
  int i=0;
  while(flag){
   System.out.println("i = " + i++);
  }
 }
 public void stop(){
  this.flag = false;
 }
}
public class StopDemo{
 public static void main(String[] args) {
  Threadlife tl = new Threadlife();
  Thread th = new Thread(tl);
  th.start();
  try {
   th.sleep(10);
  } catch (InterruptedException e) {
   
   e.printStackTrace();
  }
 
  th.stop();
 }
}


线程可以Thread类和Runnable接口来实现
使用Runnable接口的时候要覆写run()方法

线程的启动,用start()方法
线程的休眠,用sleep()方法
线程的停止,可以用修改标志位的方法来实现
    此程序中的stop()方法对标志位flag进行了修改,从而改变了输出的变量;
 休眠的时间决定于你输出时间的长短,从而影响输出的结果的多少。

原文地址:https://www.cnblogs.com/penggy/p/7475865.html