调用thread.join()时如何通知锁

时间:2014-07-01 09:54:05

标签: java multithreading

简单描述

  public static void main(String[] args ){

    Thread t = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("Thread stopped");
        }
    });

    try {
        t.start();
        t.join();
        System.out.println("task completed");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
   }

t.join()主线程等待其子线程t死亡。调用堆栈t.join()就像

一样

join -> join(0)

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

主要锁定对象t并等待通知。我在调用通知的时间和地点有些困惑。原生函数stop0()是否称之为?

1 个答案:

答案 0 :(得分:1)

看看这个:who and when notify the thread.wait() when thread.join() is called?

run()完成后,Thread子系统调用notify()。