Java中线程的执行顺序

        在多线程中,当有多个线程通过调用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();
    }
    
}

运行结果如下:

thread1
thread2
thread3

我们重复运行几次,发现每次运行的结果都是相同的,所以,使用Thread的join()方法能够保证线程的先后执行顺序。

原理分析:

因为调用子线程的join()方法,会阻塞main()方法的执行,直到子线程执行完成后,main()方法才会继续向下执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值