经典指数          
原因
1625
浏览数
0
收藏数
 

void waitForSignal()
{
    Object obj = new Object();
    synchronized(Thread.currentThread())
    {
        obj.wait();
        obj.notify();
    }
}
Which statement is true?

  • This code may throw an InterruptedException
  • This code may throw an IllegalStateException
  • This code may throw a TimeOutException after ten minutes
  • This code will not compile unless”obj.wait()”is replaced with”(Thread)obj).wait()”
  • Reversing the order of obj.wait()and obj.notify()may cause this method to complete normally

     举报   纠错  
 
切换
1 个答案

引自:https://translate.google.com/translate?hl=zh-CN&sl=zh-TW&u=http://yaya741228.pixnet.net/blog/post/78949696-%25E4%25B8%2580%25E5%25A4%25A9%25E4%25BA%2594%25E9%25A1%258Cscjp(11~15)&prev=search

解析:

这题有两个错误的地方,第一个错误是 wait() 方法要以 try/catch 包覆,或是掷出

InterruptedException 才行

 

因此答案就是因为缺少例外捕捉的

 

InterruptedException

第二个错误的地方是, synchronized 的目标与 wait() 方法的物件不相同,会有

IllegalMonitorStateException ,不过 InterruptedException 会先出现,所以这不是答案

最后正确的程式码应该是这样:

 

    

void waitForSignal() {

Object obj = new Object();

        

synchronized (obj) {

            

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

obj.notify();

}

}

 
切换
撰写答案