前言
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()时,会使主线程处于等待状态,等待子线程执行完成后才会继续向下执行