Thread、线程状态转化、方法使用

Thread、线程状态转化、方法使用

一、Thread状态关系

java 的线程的状态在Thread.state的枚举类中

public enum State {
        NEW,
        RUNNABLE,
        BLOCKED,
        WAITING,
        TIMED_WAITING,
        TERMINATED;
    }

这五种状态的描述了一个线程的生命周期,其他状态的定义在我们的业务开发中,也经常出现,比如:一个活动的提交、审核、拒绝、修改、通过、运行、关闭等类似的,线程通过如下图片进行流转。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二、状态测试

1、NEW

 Thread thread = new  Thread(()->{

        });
        System.out.println(thread.getState());

new状态是线程创建还没有启动。
2、Runnable

Thread thread = new Thread(()->{

        });
        //启动
        thread.start();
        System.out.println(thread.getState());

线程启动后start,就会进入RUnnable状态,但是此时并不一定执行,而是这个线程已经准备就绪了,可以竞争CPU资源。
3、Blocked

Object o = new Object();
        new Thread(()->{
            synchronized (o){
                try {
                    Thread.sleep(10000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

        Thread thread = new Thread(()->{
            synchronized (o){
                try {
                    o.wait();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        while (true){
            try{

            Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println(thread.getState());
        }

主要是为了让两个线程发生锁竞争
第一个synchronized获取锁后休眠
第二个synchronized获取不到锁,会被挂起
随后输出的结果都是Blocked
4、Waiting

Object obj = new Object();
        Thread thread = new Thread(() -> {
            synchronized (obj) {
                try {
                    obj.wait();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        while (true) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(thread.getState());
        }

5、TIMED_WAITING

Object object = new Object();
        Thread thread = new Thread(()->{
            synchronized (object){
                try{
                    Thread.sleep(100000);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        while (true){
            try {
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println(thread.getState());
        }

6、TERMINATED

Thread thread = new Thread(()->{

        });
        thread.start();
        System.out.println(thread.getState());
        System.out.println(thread.getState());
        System.out.println(thread.getState());

方法执行完,就进入terminated

三、Thread方法使用

一般情况下,Thread的最常用的start启动,除此之外一些其他的方法,使用不多,但是却在框架中可以看到,包括:yield、wait、notify、join
1、yield
yield方法让出CPU,但是不一定,一定让出,这样可能在一些同时启动的线程中,按照优先级保证线程的执行,也可以是一些特殊的场景,例如:这个线程很耗时,但又不重要,可以放到后面。
验证这个方法,启动50个线程,每个线程都进行1000次的加和运算,其中10个线程会执行让出CPU执行操作,如果让CPU那10个计算加和时间比较长,说明确实存在让出操作。

/**
 * @Author: wangwei
 * @Date: 2021/6/17  21:27
 * @Version: 1.0
 * @Description:
 */
public class TestYield {
    private static volatile Map<String, AtomicInteger> count = new ConcurrentHashMap<>();
    static class Y implements Runnable{
        private String name;
        private Boolean isYeild;
        public Y(String name,Boolean isYeild){
            this.name = name;
            this.isYeild = isYeild;
        }
        @Override
        public void run() {
            long l = System.currentTimeMillis();
            for (int i = 0; i < 1000; i++) {
                if (isYeild) Thread.yield();
                AtomicInteger atomicInteger = count.get(name);
                if (null == atomicInteger){
                    count.put(name, new AtomicInteger(1));
                    continue;
                }
                atomicInteger.addAndGet(1);
                count.put(name,atomicInteger);
            }
            System.out.println("线程编号:"+name+"执行时间耗时:"+(System.currentTimeMillis() - 1)
            +" (毫秒)"+(isYeild ? "让出CPU。。。。。。。。。。。。":"不让出CPU"));

        }
    }
    public static void main(String[] args) {
        for (int i = 0; i < 50; i++) {
            if (i < 10 ){
                new Thread(new Y(String.valueOf(i),true)).start();
                continue;
            }
            new Thread(new Y(String.valueOf(i),false)).start();
        }
    }
}

2、wait & notify
wait 和notify notifyall是一对方法,有一个等待,就会有个唤醒,否则程序就是夯住不动了。
3、join
join是将两个线程合并吗,不是的。
join是让线程进入wait,当线程执行完毕后,会在JVM源码中找到,它执行完毕后,其实就是执行notify,也就是等待和叫醒的操作。

public class TestJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            System.out.println("thread before");
            try{
                Thread.sleep(1000);
            }catch (Exception e){
                e.printStackTrace();
            }
            System.out.println("thread after");
        });
        thread.start();
        System.out.println("main begin");
        thread.join();
        System.out.println("main end!");
    }
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋斗的小巍

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值