对于join()方法导致当前线程等待,很多人想知道如何实现。但是,当看下面join源码的时候,觉得调用的是th1的wait,所以是th1等待,怎么会是当前线程等待呢?
public class Main{
public static void main(String[] args) {
Thread th1 = new Thread("1"){
public void run(){
//
}
};
th1.start();
th1.join();
}
}
请仔细看下面源码.其实造成当前线程等待是因为上面while(isAlive())循环,while结束就执行当前线程,但每次th1还活着就会调用wait(0),意思是释放锁0秒后唤醒自己。所以th1线程看似wait了,实际上是不断的wait->runnable的过程。可以看出,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;
}
}
join方法会是当前线程进入waiting状态
public class ThreadSample{
public static void main(String... arg) {
Thread th1 = new Thread("1"){
public void run(){
Thread th2 = new Thread("2"){
public void run(){
while(true){
}
}
};
th2.start();
try {
th2.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
th1.start();
}
}

网友评论