您好,欢迎访问一九零五行业门户网

线程--join()方法的介绍

一、join()方法,官方描述 waits for this thread to die 等待当前线程死亡;
源码:
//无参,默认调用join(0)
public final void join() throws interruptedexception {
join(0);
}
//传入两时间millis 毫秒+nanos纳秒,表示等等millis+nanos,最终还是调用了方法3
public final synchronized void join(long millis, int nanos)
throws interruptedexception {
if (millis < 0) {
throw new illegalargumentexception("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new illegalargumentexception(
nanosecond timeout value out of range);
}
if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
millis++;
}
join(millis);
}
//方法3:传入等时间,单位为毫秒,底层调用object的wait(time)
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 class threadjoin extends thread {
public void run(){
try {
this.sleep(500);
system.out.println([+new date()+]+this.getname());
} catch (interruptedexception e) {
e.printstacktrace();
}
}
public static void main(string[] args) throws exception {
int length = 5;
thread[] threads = new thread[length];
for(int i=0; i threads[i] = new threadjoin();
threads[i].start();
threads[i].join();//每个线程开启后都调用join
}
long endtime=system.currenttimemillis();
}
}
/*
output:
[sun jun 11 13:40:42 cst 2017]thread-0
[sun jun 11 13:40:43 cst 2017]thread-1
[sun jun 11 13:40:43 cst 2017]thread-2
[sun jun 11 13:40:44 cst 2017]thread-3
[sun jun 11 13:40:44 cst 2017]thread-4
如果把join()注释
结果可能每次都不一样
[sun jun 11 13:51:09 cst 2017]thread-2
[sun jun 11 13:51:09 cst 2017]thread-4
[sun jun 11 13:51:09 cst 2017]thread-1
[sun jun 11 13:51:09 cst 2017]thread-3
[sun jun 11 13:51:09 cst 2017]thread-0
*/
做事不能急,给自己一个大方向后总得一步一步来
以上就是线程--join()方法的介绍的详细内容。
其它类似信息

推荐信息