【线程/多线程】线程的执行顺序

前言

public class ThreadSort {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            System.out.println("线程1");
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("线程2");
        });
        Thread thread3 = new Thread(() -> {
            System.out.println("线程3");
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

代码很简单,声明了三个线程,分别打印文本,闲着没事儿的同学可以多次运行看一下,每次打印的顺序,并不是123,而且乱序,所以这就说明了:start()方法的调用先后不能决定线程的执行顺序

线程顺序执行

按照代码顺序来执行线程的场景其实来说也并不少见,那就上面的代码来看,怎么来让他根据start()调用的前后顺序来执行呢?

答案是:使用Thread类中的join()方法来保证执行顺序

public class ThreadSort {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            System.out.println("线程1");
        });
        Thread thread2 = new Thread(() -> {
            System.out.println("线程2");
        });
        Thread thread3 = new Thread(() -> {
            System.out.println("线程3");
        });
        thread1.start();
        thread1.join();

        thread2.start();
        thread2.join();
        
        thread3.start();
        thread3.join();
    }
}

然后多次运行就会发现,运行结果一直都是线程123的顺序

join()方法讲解

要讲解他是怎么实现顺序的,那就需要进入源码来看一下了,附上源码

public final synchronized void join(long millis)
    throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;

        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }

看源码,其实可以看得到,这个join方法使用了synchronized来修饰,就说明了这个方法同一时刻只能被一个实例或者方法调用,但是上面我们调用的时候没有入参,说以它会走到if (millis == 0)这个逻辑中,这个方法主要是判断线程是否已经启动并处于活跃状态,如果是活跃状态,则调用wait()方法,所以我们继续看一下wait()方法

public final native void wait(long timeout) throws InterruptedException;

调用这个wait()时,会使主线程处于等待状态,等待子线程执行完成后才会继续向下执行

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值