An output inside a synchronized block? Block release after call yield ()?

I create several threads and call yield() inside it.

The java.lang.Thread.yield () method causes the temporarily executed thread object to temporarily suspend and allow the execution of other threads.

Is it possible to execute other threads that also want to go inside the synchronized block?

 synchronized(this.lock) { //calling yield here. } 

thanks.

+3
source share
3 answers

As far as I know, Yield () only refuses the remaining time on the processor and returns to the queue. It does not release synchronized objects.

+5
source

yield does not accept or release locks, it just pauses the current thread. Thus, the assignment in the synchronized block will not allow the current thread to block the lock and allows other methods to enter the synchronized block. To release the lock, use the wait/notify .

From Java Language Specification

Thread.sleep causes the current executable thread to sleep (temporarily stop execution) for the specified duration, provided that the system timers and schedulers are accurate and accurate. The thread does not lose ownership of any observers and the resumption of execution will depend on the planning and availability of processors on which to execute the thread.

It is important to note that neither Thread.sleep nor Thread.yield have synchronization semantics . In particular, the compiler does not need to flush records cached into registers into shared memory before calling Thread.sleep or Thread.yield, and the compiler also needs to reload values ​​cached in registers after calling Thread.sleep or Thread.yield.

+4
source

yield allows you to switch context to other threads, so this thread will not consume the entire process of using the processor. The stream still holds the lock. It is the responsibility of the developer to take care of deadlocks.

0
source

Source: https://habr.com/ru/post/1204181/


All Articles