Simply describe
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()
The main thread waits for its subthread t to die. the call stack of t.join()
just like
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;
}
}
}
The main locked the object t and waited for notification. I have some confusion when and where the notify be called. Does the native function stop0()
call it?
Take a look at this: who and when notify the thread.wait() when thread.join() is called?
After run() finishes, notify() is called by the Thread subsystem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.