上QQ阅读APP看书,第一时间看更新
1.2.4 执行start()的顺序不代表执行run()的顺序
注意,执行start()方法的顺序不代表线程启动的顺序,即不代表run()方法执行的顺序,执行run()方法的顺序是随机的。
创建测试用的项目名称为z,MyThread.java类代码如下:
package extthread; public class MyThread extends Thread { private int i; public MyThread(int i) { super(); this.i = i; } @Override public void run() { System.out.println(i); } }
运行类Test.java代码如下:
package test; import extthread.MyThread; public class Test { public static void main(String[] args) { MyThread t11 = new MyThread(1); MyThread t12 = new MyThread(2); MyThread t13 = new MyThread(3); MyThread t14 = new MyThread(4); MyThread t15 = new MyThread(5); MyThread t16 = new MyThread(6); MyThread t17 = new MyThread(7); MyThread t18 = new MyThread(8); MyThread t19 = new MyThread(9); MyThread t110 = new MyThread(10); MyThread t111 = new MyThread(11); MyThread t112 = new MyThread(12); MyThread t113 = new MyThread(13); t11.start(); t12.start(); t13.start(); t14.start(); t15.start(); t16.start(); t17.start(); t18.start(); t19.start(); t110.start(); t111.start(); t112.start(); t113.start(); } }
图1-14 线程启动顺序与start()执行顺序无关
程序运行后的效果如图1-14所示,说明执行start()方法的顺序不代表执行run()方法的顺序,方法run()是被随机调用的,也从另外一个角度说明线程是随机执行的。