💛线程的几个状态

💛线程终止

想要终止一个线程的时候, 不推荐使用使用java里面的stop(), destory()以及一些过期的方法, 我们可以使用标志变量来控制让线程自行终止, 这相对来说是比较安全的一种方式.

package com.smile.test.thread;

public class StopThread implements Runnable {
    private boolean flag = true;

    public static void main(String[] args) {
        StopThread stopThread = new StopThread();
        new Thread(stopThread, "test").start();
        for (int i = 0; i < 1000; i++) {
            if (i == 999){
                stopThread.stop();
            }
            System.out.println(Thread.currentThread().getName() + i);
        }


    }

    @Override
    public void run() {
        while (flag){
        System.out.println(Thread.currentThread().getName() + "  is running");
        }
    }
    private void stop(){
        this.flag = false;
    }
}