1 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
先談為什么“喚醒”不了,notify不會“喚醒”MyThread3,因為阻塞不就是join方法的使命么?再說MyThread3也沒有休眠,不是一直在執(zhí)行么,何來“喚醒”之說!
最后來看看join方法的實現(xiàn),或許對你理解有幫助:
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;
}
}
}
再來談為什么有異常,其實已經(jīng)比較明確了,看注釋:
/**
* Thrown to indicate that a thread has attempted to wait on an
* object's monitor or to notify other threads waiting on an object's
* monitor without owning the specified monitor.
*/
當前線程不是該對象monitor所有者時,試圖調用其wait或者notify方法就會報這個錯,解決異常只要拿到所有者就好了,常見方法:
public class NotifyThread extends Thread{
Thread myThread ;
public NotifyThread(Thread myThread){
this.myThread=myThread;
}
public void run(){
try {
System.out.println("休眠開始");
Thread.sleep(3000);
System.out.println("休眠結束");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
synchronized(myThread){
myThread.notify();
}
System.out.println("已喚醒,讓Join失效");
}
}
添加回答
舉報