多线程中的join方法——源码分析

join方法的作用是等待线程销毁,当主线程中调用了其他线程的join方法时,主线程需要等到该线程执行完毕才可以继续执行,示例如下:

public class MyThread extends Thread
{
    public void run()
    {
        try
        {
            int value = (int)(Math.random() * 10000);
            System.out.println(value);
            Thread.sleep(value);
        } 
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }
}
public static void main(String[] args) throws Exception
{
    MyThread mt = new MyThread();
    mt.start();
    mt.join();
    System.out.println("主线程");
}

另外join方法与wait方法一样,也是在阻塞时需要释放锁,原因是join方法的实现中调用了wait方法,源码如下:

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;
        }
    }
    }

你可能感兴趣的:(Java,多线程)