【Java】多线程——使用run() 和 start() 启动线程的区别

 通过一个简单的代码来查看

package blog.hank.serivce;

public class TestTread extends Thread{
    @Override
    public void run(){
        for(int i = 0 ; i < 20; i++){
            System.out.println("I am testing" + i);
        }
    }

    public static void main(String[] args) {

        TestTread testTread = new TestTread();
        testTread.start(); // use start to run

        for(int i = 0 ; i < 20; i++){
            System.out.println("this is main function"+i);
        }
    }

}

 结果是

this is main function0
this is main function1
this is main function2
this is main function3
this is main function4
this is main function5
this is main function6
this is main function7
this is main function8
this is main function9
this is main function10
this is main function11
this is main function12
this is main function13
this is main function14
this is main function15
this is main function16
this is main function17
this is main function18
this is main function19
I am testing0
I am testing1
I am testing2
I am testing3
I am testing4
I am testing5
I am testing6
I am testing7
I am testing8
I am testing9
I am testing10
I am testing11
I am testing12
I am testing13
I am testing14
I am testing15
I am testing16
I am testing17
I am testing18
I am testing19

Process finished with exit code 0

如果是使用run来启动线程

I am testing1
I am testing2
I am testing3
I am testing4
I am testing5
I am testing6
I am testing7
I am testing8
I am testing9
I am testing10
I am testing11
I am testing12
I am testing13
I am testing14
I am testing15
I am testing16
I am testing17
I am testing18
I am testing19
this is main function0
this is main function1
this is main function2
this is main function3
this is main function4
this is main function5
this is main function6
this is main function7
this is main function8
this is main function9
this is main function10
this is main function11
this is main function12
this is main function13
this is main function14
this is main function15
this is main function16
this is main function17
this is main function18
this is main function19

Process finished with exit code 0

可以发现,使用run启动,是一种阻塞操作,而使用start,是一种交替的异步操作

也就是说,使用run的话,就是跑完run在去继续执行,而使用start是启动函数以后就继续往下执行,而线程部分则是使用另一个线程去运行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值