Thread中的join()方法

package com.qjc.thread;

public class JoinExcemple {
    // join方法就是用来同步的
    public static void main(String[] args) throws InterruptedException {
        ThreadJoinTest threadJoinA = new ThreadJoinTest("线程A");
        ThreadJoinTest threadJoinB = new ThreadJoinTest("线程B");

        Thread threadA = new Thread(threadJoinA);
        Thread threadB = new Thread(threadJoinB);
        threadA.start();
        threadA.join();// 在main线程中,调用threadA线程的join方法,主线程就会放弃cpu,等待threadA执行完毕后再执行
        threadB.start();
    }
}

class ThreadJoinTest implements Runnable {
    String threadName;

    public ThreadJoinTest(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public void run() {
        for (int i = 0; i < 100000; i++) {
            System.out.println(this.threadName + "----" + i);
        }
    }

}

 大家可以看一下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);//如果活着则等待,参数为0,说明必须等待调用join()方法的线程执行完毕后再执行
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
/**
 * Tests if this thread is alive. A thread is alive if it has
 * been started and has not yet died.
 *
 * @return  <code>true</code> if this thread is alive;
 *          <code>false</code> otherwise.
 * 如果该线程已经启动,但是还没有结束,则就是活着的
 */
public final native boolean isAlive();

/**
 * Causes the current thread to wait until either another thread invokes the
 * {@link java.lang.Object#notify()} method or the
 * {@link java.lang.Object#notifyAll()} method for this object, or a
 * specified amount of time has elapsed.
 * 该线程会一直等待,直到被唤醒
 */
public final native void wait(long timeout) throws InterruptedException;

所以,从源码可以看出,主线程中调用了ThreadA的join()方法,则相当于调用了ThreadA的wait()方法,

当ThreadA线程执行完后会调用自身的notifyAll()方法唤醒主线程,从而达到了同步的目的

原文地址:https://www.cnblogs.com/java-spring/p/8872796.html