有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (2) 个答案

  1. # 1 楼答案

    除非javadoc提到一个对象的监视器(比如Object.wait()),否则您应该假设任何锁都将继续被持有。因此:

    Does this mean yield will not release the lock?

    Does the current thread release the lock?

    没有

  2. # 2 楼答案

    sleep将线程置于等待状态,yield将线程直接返回到就绪池。(因此,如果线程生成,它可以直接从运行到就绪池,再由调度程序挑选,而无需等待。)两者都与锁定无关

    Java Language Specification开始:

    Thread.sleep causes the currently executing thread to sleep (temporarily cease execution) for the specified duration, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors, and resumption of execution will depend on scheduling and the availability of processors on which to execute the thread.

    It is important to note that neither Thread.sleep nor Thread.yield have any synchronization semantics. In particular, the compiler does not have to flush writes cached in registers out to shared memory before a call to Thread.sleep or Thread.yield, nor does the compiler have to reload values cached in registers after a call to Thread.sleep or Thread.yield.

    For example, in the following (broken) code fragment, assume that this.done is a non-volatile boolean field:

    while (!this.done)
         Thread.sleep(1000);
    

    The compiler is free to read the field this.done just once, and reuse the cached value in each execution of the loop. This would mean that the loop would never terminate, even if another thread changed the value of this.done.