多线程的执行顺序
在并发程序设计中,由于要关注到流水线的效率,会乱序执行,在Java多线程中,每个线程也不是按照顺序执行的。
public class Main {
public static void main(String[] args){
Thread thread=new Thread(new Runnable() {
public void run() {
System.out.println("hello");
}
});
thread.start();
System.out.println("Main");
}
}
以上程序的运行结果会出现:
Main
hello
这就说明在多线程中,代码运行的结果与代码被调用的顺序是无关的。以下程序更能说明:
public class Main {
public static void main(String[] args){
Thread thread1=new Thread(new TheThread());
Thread thread2=new Thread(new TheThread());
Thread thread3=new Thread(new TheThread());
thread1.start();
thread2.start();
thread3.start();
}
}
class TheThread implements Runnable{
public void run() {
for(int i=0;i<10;i++)
System.out.println(Thread.currentThread().getId()+":"+i);
}
}
以上程序的运行结果可以自己证明。
运行以上程序,查看结果