返回信息流join()方法是说等待该线程消亡,内部使用wait()方法实现的。但请问是具体是怎么实现的呢?
下面一个例子
join()方法示例:
public class Easy {
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
try {
mt.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main over");
}
}
class MyThread extends Thread{
public void run(){
int secondValue = (int) (Math.random()*10000);
System.out.println(secondValue);
try {
Thread.sleep(secondValue);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出:
6484
main over //main线程最后结束
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); //请问这个wait()是谁wait(),wait()之后呢?
now = System.currentTimeMillis() - base;
}
}
}
大神们帮忙分析示例的join()是怎么运行的?
这是一条镜像帖。来源:北邮人论坛 / java / #45128同步于 2015/10/30
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
Java线程join()方法
dongqing
2015/10/30镜像同步3 回复
订阅后,新回复会通过你的通知中心匿名送达。
3 条回复
【 在 lee8464 的大作中提到: 】
: 你是不是源码找的不对啊?
: 这个源码join带参的,你调用的join又是无参。
: 我也不懂,瞎扯的。
内部调用的是有参的