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