Thread 类中,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;
}
}
}
比如:
public static void main(String[] args) throws InterruptedException {
System.out.println(Thread.currentThread().getName() + " at begin ");
Thread t1 = new Thread(new Runnable(){
public void run() {
System.out.println(" Thread t1 stats");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread t1 ends");
}
});
t1.start();
t1.join();// t1调用join();t1会wait(0),那么t1是如何让main线程等待的呢
System.out.println(Thread.currentThread().getName() + " at end ");
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于