Does thread.yield() lose the lock on object if called inside a synchronized method?

前端 未结 3 455
感情败类
感情败类 2020-12-15 11:19

I understand that Thread.currentThread().yield() is a notification to thread scheduler that it may assign cpu cycle to some other thread of same priority if any

相关标签:
3条回答
  • 2020-12-15 11:28

    In Java Language specification
    17.3 Sleep and Yield
    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.

    My comment:

    In java's early days, when it did not really supported parallel executions, but only concurrent (green threads), yield() was suspending the current thread, and the jvm was picking up another thread to resume. Now-days, yield does not have much meaning as usually the tread scheduling is on OS level.

    So, yield is just a hint to the JVM that current thread wants to take a rest and nothing else, it is up to the thread scheduler to decide what to do. yield does not have any synchronization semantic. If thread holds lock, it will continue to hold it.

    0 讨论(0)
  • 2020-12-15 11:29

    No. Thread.yield() is not like Object.wait(). It just gives up control to allow a thread switch. It will have no effect on the concurrency of your program.

    There is no guarantee which thread the scheduler will run after a yield.

    0 讨论(0)
  • 2020-12-15 11:45

    Only wait methods of the Object class release the intrinsic lock of the current instance (the thread may have other locks acquired, they don't get released). Yield, sleep, join do not bother about locks. However, join is a little more special, you are guaranteed to see all the changes made by the thread you're waiting for to finish.

    0 讨论(0)
提交回复
热议问题