线程五大状态(停止,休眠,礼让,join,state)

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

停止线程


  • 不推荐使用jdk提供的 stop(), destroy(),方法。
  • 推荐线程自己停下来。
  • 建议使用一个标志位进行终止变量,当 flag=false,则线程终止。
// 停止线程
public class StopThread implements Runnable {

    // 1。设置一个标志位
    private boolean flage=true;

    @Override
    public void run() {
        int i=0;
        while (flage) {
            System.out.println("run...thread--->"+i++);
        }
    }

    //2.设置一个公开的方法停止线程,转换标志位
    public void stopThread() {
        this.flage=false;
    }

    public static void main(String[] args) {

        StopThread stopThread = new StopThread();
        new Thread(stopThread).start();

        for (int i = 0; i < 1000; i++) {

            System.out.println("main..."+i);
            if (i==500) {
                stopThread.stopThread();
                System.out.println("run。。。停止了");
            }

        }

    }
}

线程休眠


  • sleep(时间)指当前线程阻塞的毫秒数(1000毫秒=1秒)
  • sleep存在异常 InterruptedException
  • sleep时间达到后,线程进入就绪状态
  • sleep可以模拟网络延时,倒计时等
  • 每一个对象都有锁,sleep不会释放锁 【⭐】

模拟延时:放大问题的发生性

模拟倒计时

public class TestSleep {

    public static void main(String[] args) throws InterruptedException {
       // new TestSleep().tenDown();  // 倒计时
        
         // 打印当前系统时间
        Date date= new Date(System.currentTimeMillis()); // 获取当前系统时间

        while (true) {
            Thread.sleep(1000);
            System.out.println(new SimpleDateFormat("HH:mm:ss").format(date));
            date = new Date(System.currentTimeMillis());  // 更新当前时间
        }
        
        
    }

    // 模拟倒计时
    public void tenDown() throws InterruptedException {

        int num = 10;
        while (true) {
            if (num<0) {
                break;
            }
            Thread.sleep(1000);
            System.out.println(num--);
        }
    }

}

礼让(yield)


  • 让正在执行的线程暂停,但不阻塞

  • 将线程从运行状态转为就绪状态

  • 礼让不一定成功,看cup心情

// yield() 礼让不一定成功
public class TestYield {

    public static void main(String[] args) {
        MyYield myYield =new MyYield();

        new Thread(myYield,"a").start();
        new Thread(myYield,"b").start();
    }

}

class MyYield implements Runnable {

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName()+"线程开始执行");
        Thread.yield(); // 礼让
        System.out.println(Thread.currentThread().getName()+"线程结束执行");
    }
}

Join(插队)


  • 待此线程完成后,在执行其他线程,其他线程阻塞
  • 可以想象为插队
  • 非常霸道,不建议使用

代码示例

public class TestJoin implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            System.out.println("VIP-->"+i);
        }
    }


    public static void main(String[] args) throws InterruptedException {
        TestJoin join = new TestJoin();

        Thread thread = new Thread(join);
        thread.start();

        for (int i = 0; i < 500; i++) {
            if (i==200) {
                thread.join();  // 插队
            }
            System.out.println("main--->"+i);
        }
    }
}

state(线程状态)


[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qZM53SOD-1656680587064)(C:\Users\28416\AppData\Roaming\Typora\typora-user-images\image-20220701204206205.png)]

// 观察线程状态
public class TestState {

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread( ()->{
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println("============");
        });

        // 观察状态
        Thread.State state = thread.getState();
        System.out.println(state);  //new

        // 观察启动后
        thread.start();
        state = thread.getState();
        System.out.println(state); // run

        // 只要线程没终止,就一直输出状态
        while (state != Thread.State.TERMINATED) {
            Thread.sleep(100);
            state = thread.getState(); // 更新线程状态
            System.out.println(state);
        }

    }

}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值