欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Thread() join()

程序员文章站 2022-06-21 11:29:38
...
public class JoinMessages extends Thread {


    public static void main(String[] args) {
        JoinMessages joinMessages = new JoinMessages();
        joinMessages.start();
    }

    public void run(){
        System.out.println(Thread.currentThread().getName()+ ":start");
        try {
            System.out.println("join start");
            join(4000);
            System.out.println("join stop");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

来看下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;
            }
        }
    }

其实调用了wait()

public final native void wait(long timeout) throws InterruptedException;
相关标签: 线程 thread