Thread的方法join()使用

join()的作用:Waits for this thread to die.等待线程对象销毁。
在Thread源码中可以看到join源码是使用了wait()方法来实现等待功能。

因为join()内部使用了wait()方法实现,wait方法被调用后线程会释放锁,因此join方法也具有释放锁的特点。

这也是join()、wait()和sleep()的区别,sleep是不会释放锁的。

JDK1.8中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能够使线程排队运行。

/**
 * @author monkjavaer
 * @date 2018/12/15 16:36
 */
public class JoinThread implements Runnable{
    @Override
    public void run() {
        System.out.println("I am JoinThread run ...");
        try {
            TimeUnit.MILLISECONDS.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

 join()测试:

public class JoinTest {
    public static void main(String[] args) {
        try {
            Thread thread = new Thread(new JoinThread());
            thread.start();
            thread.join();
            System.out.println("....after JoinThread.....");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  输出:

I am JoinThread run ...
....after JoinThread.....

 

原文地址:https://www.cnblogs.com/monkjavaer/p/10123853.html