join
public final void join() throws InterruptedException {
join(0);
}
该方法会一直等待直到调用的方法结束
public final synchronized void join(long millis)throws InterruptedException {}
该方法可以指定终止的最长时间
测试方法示例 1
public class MyThead implements Runnable{
Thread t;
public MyThead(String threadName){
t = new Thread(this,threadName);
System.out.println(t);
t.start();
}
@Override
public void run() {
for(int i=0;i<5;i++){
try {
System.out.println(t.getName() + "\t:\t" + i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MyThead m1 = new MyThead("one");
m1.t.join();
System.out.println("m thread is over");
输出
Thread[one,5,main]
one : 0
one : 1
one : 2
one : 3
one : 4
m thread is over
测试方法示例 2
MyThead m1 = new MyThead("one");
m1.t.join(1000);
System.out.println("m thread is over");
输出
Thread[one,5,main]
one : 0
one : 1
m thread is over
one : 2
one : 3
one : 4
本文详细介绍了Java中Thread的join方法,包括无参数版本和带超时参数的版本。join方法用于线程同步,使得当前线程等待指定线程执行完毕。通过两个测试示例展示了join方法如何影响线程执行顺序和超时效果,帮助理解其工作原理。
718

被折叠的 条评论
为什么被折叠?



