11 停止线程

发布时间 2023-09-05 21:27:59作者: 被占用的小海海

package ThreadDemo;

// 线程的几个状态:创建,就绪,执行,阻塞,死亡
   // 测试停止线程
    /*
    1. 线程正常停止
    2. 设置标志位 flag
    3. 不要使用jdk自带的 stop(),和 destroy()方法,过时了
     */
public class Test11_Stop implements Runnable{
    boolean flag=true;

    @Override
    public void run() {
        int i=1;
        while (flag){
            System.out.println("run Thread"+i++);
        }
    }

    public void stop(){
        flag=false;
    }

    public static void main(String[] args) {
        Test11_Stop test11Stop = new Test11_Stop();
        new Thread(test11Stop).start();
        for (int i = 0; i < 80000000; i++) {
            if (i==70000000){
                test11Stop.stop();
                System.out.println("停止线程");
            }
        }
    }
}