thead.join方法 原理

来源:互联网 发布:编程中的ret是什么意思 编辑:程序博客网 时间:2024/05/16 09:13
join方法,可以控制异步线程的执行顺序。
/** * @author zack */public class HelloJoin {public static void main(String[] args) {Thread thread1 = new Thread(new Runnable() {public void run() {System.out.println(Thread.currentThread().getName()+"-----I'm coming");}});thread1.start();try {thread1.join();} catch (InterruptedException e) {}if (thread1.isAlive()) {System.out.println(Thread.currentThread().getName() + "---I'm alive");}else{System.out.println(Thread.currentThread().getName() + "---I'm over");}System.out.println(Thread.currentThread().getName() + "--over");}}


thread1是异步线程,thread1执行完之后,main才会继续执行直到main线程结束。
Thread-0-----I'm comingmain---I'm overmain--over

源代码:
 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;            }        }    }


原理: