在多线程中,当有多个线程通过调用Thread的start()方法启动时,每个线程的执行顺序是不确定的。也就是说,连续创建多个线程后,调用start()方法的顺序并不能决定线程实际的执行顺序。
写个例子验证下:
public class Test {
public static void main(String[] args){
Thread thread1 = new Thread(() -> {
System.out.println("Thread1");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread2");
});
Thread thread3 = new Thread(() -> {
System.out.println("Thread3");
});
thread1.start();
thread2.start();
thread3.start();
}
}
我们创建了三个不同的线程,thread1、thread2和thread3,接下来,通过调用thread1.start()、thread2.start()和thread3.start()方法来启动三个线程。
运行main方法,结果如下:
thread1
thread2
thread3
再次运行时,结果如下:
Thread1
Thread3
Thread2
注意:每个人运行的情况可能都不一样。
继续重复运行几次,发现每次运行的执行顺序可能不同。说明线程的启动顺序并不能决定线程的执行顺序。
如何确保线程的执行顺序
那么如何确保线程的执行顺序呢?
可以通过使用Thread类中的join()方法来确保线程的执行顺序。
再写个例子验证下:
public class Test {
public static void main(String[] args){
Thread thread1 = new Thread(() -> {
System.out.println("Thread1");
});
Thread thread2 = new Thread(() -> {
System.out.println("Thread2");
});
Thread thread3 = new Thread(() -> {
System.out.println("Thread3");
});
thread1.start();
thread1.join();
thread2.start();
thread2.join();
thread3.start();
thread3.join();
}
}
运行结果如下:
扫描二维码关注公众号,回复:
15556355 查看本文章
thread1
thread2
thread3
我们重复运行几次,发现每次运行的结果都是相同的,所以,使用Thread的join()方法能够保证线程的先后执行顺序。
原理分析:
因为调用子线程的join()方法,会阻塞main()方法的执行,直到子线程执行完成后,main()方法才会继续向下执行。