Thread.join
需要用到子线程的处理结果,这个时候就要用到 "子线程对象.join();"方法了,主线程会等子线程执行完后再执行。
/** * Waits at most <code>millis</code> milliseconds for this thread to * die. A timeout of <code>0</code> means to wait forever. */ 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; } } }
如果线程被生成了,但还未被起动,isAlive()将返回false,调用它的join()方法是没有作用的。
public class TestJoin implements Runnable { public static void main(String[] sure) throws InterruptedException { Thread t = new Thread(new TestJoin()); long start = System.currentTimeMillis(); t.start(); t.join(1000); System.out.println(System.currentTimeMillis() - start); System.out.println("Main finished"); } @Override public void run() { synchronized (Thread.currentThread()) { for (int i = 1; i <= 5; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("睡眠" + i); } System.out.println("TestJoin finished"); } } }
睡眠1
睡眠2
睡眠3
睡眠4
睡眠5
TestJoin finished
5022
Main finished
join(1000)表示main方法只会等待线程t执行1s,1s结束后又回到抢占模式,只不过程序中没有被main方法抢占到锁所以还是5s,如果被main抢到了,那还是main先结束。就相当于你的t线程在休眠1s而你的main也刚好等待t等了1s俩个重合了,所以还是5s

浙公网安备 33010602011771号