有人可以告诉我线程开始执行的顺序吗?我写了以下代码
class NewThread implements Runnable {
Thread t;
NewThread() {
//creating a second thread.
t=new Thread(this,"Demo Thread");
System.out.println("Child Thread:"+t);
t.start();
}
public void run() {
try {
for(int i=0;i<5;i++) {
System.out.println("Child Thread:"+i);
Thread.sleep(3000);
}
} catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
System.out.println("Exiting Child Thread");
}
}
还有这个
public class ThreadDemo {
public static void main(String args[]) {
new NewThread();
try {
for(int i=0;i<5;i++) {
System.out.println("Main Thread:"+i);
Thread.sleep(3000);
}
} catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
System.out.println("Exiting Main Thread");
}
}
当我执行这段代码时,我得到了许多不同的输出集。
Child Thread:Thread[Demo Thread,5,main]
Main Thread:0
Child Thread:0
Child Thread:1
Main Thread:1
Main Thread:2
Child Thread:2
Main Thread:3
Child Thread:3
Main Thread:4
Child Thread:4
Exiting Main Thread
Exiting Child Thread
另一个,
Child Thread:Thread[Demo Thread,5,main]
Main Thread:0
Child Thread:0
Child Thread:1
Main Thread:1
Child Thread:2
Main Thread:2
Child Thread:3
Main Thread:3
Child Thread:4
Main Thread:4
Exiting Child Thread
Exiting Main Thread
为什么会出现这种情况?线程顺序永远不会相同吗?如果有人能给我指点线程和示例的基础知识,那就太好了。PS:我是线程新手,这是我的第一个线程程序。提前致谢。