Java并发(六)----线程start、run、state方法

文章对比了在Java中直接调用run()方法和使用start()启动线程的差异。调用run()方法实际上在当前线程(这里是main线程)中执行,而start()会创建新线程并异步执行run()里的代码。同时,文章展示了线程从NEW到RUNNABLE状态的转变。
摘要由CSDN通过智能技术生成

1、start 与 run

调用 run

public static void main(String[] args) {
    Thread t1 = new Thread("t1") {
        @Override
        public void run() {
            log.debug(Thread.currentThread().getName());// 打印线程名称
            FileReader.read(Constants.MP4_FULL_PATH);// 输出start 和 end  具体逻辑可忽略,只关注输出即可
        }
    };
​
    t1.run();
    log.debug("do other things ...");
}

输出

19:39:14 [main] c.TestStart - main
19:39:14 [main] c.FileReader - read [1.mp4] start ...
19:39:18 [main] c.FileReader - read [1.mp4] end ... cost: 4227 ms
19:39:18 [main] c.TestStart - do other things ...

程序仍在 main 线程运行,FileReader.read() 方法调用还是同步的

调用 start

将上述代码的 t1.run() 改为

t1.start();

输出

19:41:30 [main] c.TestStart - do other things ...
19:41:30 [t1] c.TestStart - t1
19:41:30 [t1] c.FileReader - read [1.mp4] start ...
19:41:35 [t1] c.FileReader - read [1.mp4] end ... cost: 4542 ms

程序在 t1 线程运行,FileReader.read() 方法调用是异步的

小结

  • 直接调用 run 是在主线程中执行了 run,没有启动新的线程

  • 使用 start 是启动新的线程,通过新的线程间接执行 run 中的代码

2、state

    public static void main(String[] args) {
        Thread t1 = new Thread("t1") {
            @Override
            public void run() {
                log.debug("running...");
            }
        };
​
        System.out.println(t1.getState());
        t1.start();
        System.out.println(t1.getState());
    }

输出

NEW
RUNNABLE
22:19:28.957 c.Test5 [t1] - running...
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

|旧市拾荒|

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

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

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

打赏作者

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

抵扣说明:

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

余额充值