java thread join实现原理
所属分类 java
浏览量 1372
public static void main(String[] args) throws Exception {
System.out.println("JoinTest start "+new Date());
MyThread myThread = new MyThread();
myThread.start();
// 主线程等待 myThread 执行完成
myThread.join();
System.out.println("JoinTest done "+new Date());
}
private static class MyThread extends Thread{
public void run(){
// sleep 2000 ms
Utils.doSleep(2000);
}
}
调用目标线程的join方法,当前线程会被阻塞,等待目标线程执行完成
join使用 wait 与 notifyAll 实现 典型的等待通知机制
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 方法 使用 synchronized 线程对象作为锁对象,符合使用wait的经典套路
synchronized(obj) {
while(!condition) {
obj.wait();
}
doSomething();
}
notifyAll 由 jvm 调用 , 具体可以看jvm 的 c++ 代码
void JavaThread::exit(bool destroy_vm, ExitType exit_type)
static void ensure_join(JavaThread* thread) {
Handle threadObj(thread, thread->threadObj());
ObjectLocker lock(threadObj, thread);
thread->clear_pending_exception();
java_lang_Thread::set_thread_status(threadObj(), java_lang_Thread::TERMINATED);
java_lang_Thread::set_thread(threadObj(), NULL);
// notify_all !!!!!
lock.notify_all(thread);
thread->clear_pending_exception();
}
上一篇
下一篇
NoClassDefFoundError和ClassNotFoundException异常的区别
进程线程与协程的区别
ExecutorService中submit和execute的区别
java线程池shutdown和shutdownNow的区别
JAVA虚拟机关闭钩子Shutdown Hook使用
职场十大通用准则