线程停止

不要用自带的stop方法,设置flag标志位停止线程。

public class TestThreadStop implements Runnable{
   private boolean flag=true;
   @Override
   public void run() {
       int i=0;
       while (flag){
           System.out.println("i love u"+i++);
      }
  }
   public void stop(){
       this.flag=false;
       System.out.println("不爱了哦");
  }

   public static void main(String[] args) {
       TestThreadStop testThreadStop = new TestThreadStop();
       Thread thread = new Thread(testThreadStop);
       thread.start();
       for (int i = 0; i < 1000; i++) {
           System.out.println("really"+i);
           if (i==900){
               testThreadStop.stop();
          }

      }
  }
}

 

posted on 2021-03-07 15:34  要给小八赚罐头钱  阅读(45)  评论(0)    收藏  举报