join方法的作用
thread.join()方法用于把指定的线程加入到当前线程中,把当前线程的CPU执行时间让给另一个线程。比如在线程B中调用了线程A的Join()方法,直到线程A执行完毕后,才会继续执行线程B。
threadA.join(); //把当前线程执行时间让给threadA线程,直到threadA执行完毕才会继续执行当前线程
threadA.join(1000); //把当前线程执行时间让给threadA线程,1000毫秒后,A、B两个线程再重新竞争
join方法的源码如下,可以看出是通过while和wait的方式进行控制:
/** * Waits at most <code>millis</code> milliseconds for this thread to * die. A timeout of <code>0</code> means to wait forever. */ //此处A timeout of 0 means to wait forever 字面意思是永远等待,其实是等到t结束后。 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; } } }
下面这个程序的输出结果是多少?A:0 B:1000 C:1 D:不确定
public class ThreadTest extends Thread { public static int a = 0; public void run() { for (int k = 0; k < 100000; k++) { a = a + 1; } } public static void main(String[] args) throws Exception { Thread t = new ThreadTest(); t.start(); t.join(1); System.out.println(a); } }
答案是:D。因为t.start()只是让线程进入了RUNNABLE状态,但并不一定在1毫秒内执行到t线程的run方法。如果没有走进t线程的run方法,直接执行了主线程的打印语句,则输出结果为0;如果进入了t线程的run方法,并且在1毫秒内将t线程的run方法执行完毕,则输出结果为100000;否则,可能是0~100000之间的任意数字。因此最终答案不能确定