Java 线程停止

132 阅读1分钟

要点

  • 官方不推荐(@Deprecated)直接用stop
  • 最好让线程自己停止
  • 自己设置标志位(flag)让线程开始和停止
  • 自己写stop()方法,转换标志位。

用例


public class StopThread {
    public static void main(String[] args) {
        Tt tt = new Tt();
        new Thread(tt).start();
        for (int i = 0; i < 100; i++) {
            System.out.println("main线程执行中。。。。"+i);
            if(i==98){
                System.out.println("Tt线程停止");
                tt.stop();
            }
        }
    }
}
class Tt implements Runnable{
    boolean flag = true;//设置标志位,可让线程运行
    int i = 0;
    @Override
    public void run() {
        while (flag){
            System.out.println("Tt线程执行中。。。。"+i++);
        }
    }
    public void stop(){//转换标志位
        this.flag = false;
    }
}