java中的线程停止

前言

在线程停止上,java一开始我们准备了很多停止线程的方法,其中最常用的方法就是在Thread类里面的stop()方法,但是在jdk8出现后,这种方法就被淘汰了,紧接着我们停止线程需要自己写一个停止线程的方法。

方法如下
  1. 首先我们需要重新写一个类class TestStop类,继承runnable接口,重写run方法。

  1. 在run方法里面写上while循环,while(flag)中的flag来判断是否循环停止,flag的初始值为true。

  1. 书写线程停止方法stop(),方法里面就写this.flag=flase。

  1. 主函数里面new一下TestStop类,将这个类抛入到Thread thread = new Thread(teststop)里面,然后开启线程thread.start()。

  1. 让线程执行多少次之后停止,运用for循环+if语句来做到。

主要代码
package ThreadStudy.TestThread;

public class TestStop implements Runnable{

    public boolean flag=true;


    @Override
    public void run() {
        int i=0;
     while (flag){
         System.out.println("我在学习stop"+i++);
     }
    }

    public void stop(){//线程停止函数
        this.flag=false;
    }


    public static void main(String[] args) {
        TestStop testStop = new TestStop();

       new Thread(testStop).start();

        for (int i = 0; i < 1000; i++) {
            System.out.println("main"+i);
            if (i==900){//执行900次线程停止
                testStop.stop();
                System.out.println("线程停止");
            }
        }

    }
}