证明题:如何证明线程创建需要消耗

学到线程池的时候,大家都知道为什么要用线程池,因为线程的创建和销毁需要消耗。别人这么说了,你也就这么记了,今天就来验证下。 

    public static void main(String[] args)  {
        MyThread t1 = new MyThread("t1");//会打印信息,这里就不展现了
        MyThread t2 = new MyThread("t2");
        System.out.println(1);
        t1.start();
        System.out.println(2);
        t2.start();
    }

打印:

1

2

this is  t1 线程

this is  t2 线程

可以看到主线程main 中打印的 1  2 先跑了,线程还在创建中,还没开始执行。

    public static void main(String[] args) throws InterruptedException {
        MyThread t1 = new MyThread("t1");//会打印信息,这里就不展现了
        MyThread t2 = new MyThread("t2");
        System.out.println(1);
        t1.start();
        Thread.sleep(4000);
        System.out.println(2);
        t2.start();
    }

打印:

1

this is t1 线程

2

this is  t2 线程

而这里主线程睡眠4秒,这时候就打印出了进入t1线程的情况,说明线程开始运行了。

 

因此,由第1块代码可以看出了,线程创建需要消耗时间,从而优先打印了 主线程中的1 和2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值