1 回答
TA贡献2003条经验 获得超2个赞
先谈为什么“唤醒”不了,notify不会“唤醒”MyThread3,因为阻塞不就是join方法的使命么?再说MyThread3也没有休眠,不是一直在执行么,何来“唤醒”之说!
最后来看看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;
}
}
}
再来谈为什么有异常,其实已经比较明确了,看注释:
/**
* 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失效");
}
}
添加回答
举报