日期:2014-05-20  浏览次数:20824 次

问个147中关于线程的题目?
54.   Which   statement   is   true?
A.   If   only   one   thread   is   blocked   in   the   wait   method   of   an   object,   and   another   thread   executes   the   notify   on   that   same   object,   then   the   first   thread   immediately   resumes   execution.  
B.   If   a   thread   is   blocked   in   the   wait   method   of   an   object,   and   another   thread   executes   the   notify   method   on   the   same   object,   it   is   still   possible   that   the   first   thread   might   never   resume   execution.  
C.   If   a   thread   is   blocked   in   the   wait   method   of   an   object,   and   another   thread   executes   the   notify   method   on   the   same   object,   then   the   first   thread   definitely   resumes   execution   as   a   direct   and   sole   consequence   of   the   notify   call.  
D.   If   two   threads   are   blocked   in   the   wait   method   of   one   object,   and   another   thread   executes   the   notify   method   on   the   same   object,   then   the   first   thread   that   executed   the   wait   call   first   definitely   resumes   execution   as   a   direct   and   sole   consequence   of   the   notify   call.  
英文水平不够,看着挺别扭的,帮忙解释一下了

------解决方案--------------------
B(true). If a thread is blocked in the wait method of an object, and another thread executes the notify method on the same object, it is still possible that the first thread might never resume execution.
如果一个线程被一个对象的wait方法阻塞,当另一个线程调用了同一个对象的notify方法后,这个线程可能永远不会唤醒
------解决方案--------------------
A. 如果仅有一个线程阻塞在一个对象的wait方法中,而另一个线程执行了同一个对象的notify方法,那么第一个线程立即恢复执行。
B. 如果一个线程阻塞在一个对象的wait方法中,而另一个线程执行了同一个对象的notify方法,那么第一个线程仍然有可能永远不能恢复执行。
C. 如果一个线程阻塞在一个对象的wait方法中,而另一个线程执行了同一个对象的notify方法,那么作为notify调用的直接、唯一的结果,第一个线程必定恢复执行。
D. 如果两个线程阻塞在一个对象的wait方法中,而另一个线程执行了同一个对象的notify方法,那么作为notify调用的直接、唯一的结果,执行wait调用的第一个线程必定恢复执行。

虽然容易翻译,但是很难判断……
学得不够扎实啊。

A的错误在于,那个阻塞的线程不会“立即”恢复执行,它还要重新获得对象的监视器才行,也就是要和其他synchronize了这个对象的线程争抢监视器。
C的错误在于,notify调用的直接结果是允许阻塞在wait方法的那个线程重新加入对该对象的争夺,当该线程获得了该对象的监视器后,才能恢复执行。
D的错误除了C的以外,还有一点:线程的唤醒顺序和它们调用wait的顺序并不保证一致,据说这是为了给实现虚拟机的人留有自己选择算法的机会。
------解决方案--------------------
学习中哈,嘿嘿!
------解决方案--------------------
B

下面是官方的解释:
http://java.sun.com/docs/books/tutorial/essential/concurrency/guardmeth.html
------解决方案--------------------
唤醒在此对象监视器上等待的单个线程。如果所有线程都在此对象上等待,则会选择唤醒其中一个线程。选择是任意性的,并在对实现做出决定时发生。线程通过调用其中一个 wait 方法,在对象的监视器上等待。

还有应该尽量使用notifyAll(),这样才使所有线程都有被唤醒的机会。
------解决方案--------------------
哪一陈述是真实的?
A. 如果只有一条线在物体的等候方法中被阻塞,而且另外的一条线运行那在那个相同的物体上通知,然后第一条线立刻重新开始实行。
B. 如果一条线在物体的等候方法中被阻塞,而且另外的一条线运行那通知在相同的物体上的方法,它仍然是可能的第一线力气从不重新开始实行。
C. 如果一条线在物体的等候方法中被阻塞,而且另外的一条线运行那通知在相同的物体上的方法, 然后第一条线明确地重新开始实行当直接的和唯一的结果那通知呼叫。