java thread join 源码解析

来源:互联网 发布:mac装双系统win10 编辑:程序博客网 时间:2024/05/21 17:39

示例代码

   public static void main(String[] args) {            HttpThreadMultiUrl hackWeb = new HttpThreadMultiUrl("MultiUrlThread1");            hackWeb.start();            try {                hackWeb.join();            } catch (Exception e) {                // TODO: handle exception            }    }

上述是main函数代码,启动了一个自定义的线程HttpThreadMultiUrl,具体行为我们不需要关注,可以是一段操作或者是一个循环或是睡眠一段。
join方法则会使得main thread阻塞,等待join返回,这个join实际是等hackweb线程的run方法结束才返回的。

源码

    public final void join() throws InterruptedException {        join(0);    }

调用了带有参数的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;            }        }    }

上面我们说了join会等待线程结束再返回,这里通过wait不断等待,并通过isAlive去查询状态,这两个函数是native的函数。

0 0
原创粉丝点击