线程间通信_等待/通知之Thread.join()

Thread.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;
            }
        }
    }

从源码可以看出,只要线程是alive的,就一直调用wait方法,直到线程终止。也就是如果在一个线程中,启动了另一个线程,并调用该线程的wait方法,那么当前线程就会阻塞,知道另一个线程执行完毕,才去向下执行.

简单表示:

Thread1{

run{

thread2.start();
thread2.join();
System.out.print("上面线程执行完毕,我才继续执行,没有执行完,我就阻塞")

}

}

代码验证:

package com.ftf.thread.test;

public class ThreadJoinDemo {
	public static void main(String[] args) throws InterruptedException {
		Thread t = new Thread(new Runnable() {
			public void run() {
				System.out.println("线程0执行...end...");
			}
		});
		t.start();
		for (int i = 0; i < 10; i++) {
			JoinThread jt = new JoinThread(t, i);
			jt.start();
			t = jt;
		}
	}
}

class JoinThread extends Thread {
	private Thread t;
	private int i;

	public JoinThread(Thread t, int i) {
		this.t = t;
		this.i = i;
	}

	@Override
	public void run() {
		try {
			t.join();
			System.out.println("线程" + (i + 1) + "执行....end...");
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}

打印结果:

线程0执行...end...
线程1执行....end...
线程2执行....end...
线程3执行....end...
线程4执行....end...
线程5执行....end...
线程6执行....end...
线程7执行....end...
线程8执行....end...
线程9执行....end...
线程10执行....end...


你可能感兴趣的:(多线程,多线程学习)