java中join用法

今天又把join的用法大概看了一下,其实理解起来,还是比较简单。用个简单的例子说明一下吧。

1、通过下面的例子,可以看到说出结果中首先全部是是Thread-1,之后才会是Thread-2,这是因为在主线程中调用了thread1的join方法,就等于将主线程和thread1的执行方式由并行改为了串行,也就是必须当thread1全部执行结束之后,才会调用thread2的方法。这就可以解释为啥先全部是thread-1之后才会有thread-2了。

public class TestJoin {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new JoinThread());;
        Thread thread2 = new Thread(new JoinThread());
        
        thread1.start();
        thread1.join();
        thread2.start();
        
    }
    
    static class JoinThread implements Runnable {

        @Override
        public void run() {
            for(int i=0; i<100; i++) {
                try {
                    System.out.println(Thread.currentThread().getName());
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 2、关于join方法其实还可以提交过期时间,也就是在执行到达预定时间后,执行方式将继续以并行的方式执行。

thread1.join(10);//表示10ms后,将结束join。

3、通过join的源码中可以到,其实join的本质还是调用的wait方法。关于wait方法的实现,就无法分析了。因为它是个native方法,无法进一步查看源码了

  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;
            }
        }
    }
原文地址:https://www.cnblogs.com/woniu4/p/8506083.html