Reputation: 702
I am creating a multiple threads and calling yield()
inside it.
The java.lang.Thread.yield() method causes the currently executing thread object to temporarily pause and allow other threads to execute.
Will It be possible for other threads to execute which also want to go inside synchronized block?
synchronized(this.lock)
{
//calling yield here.
}
thanks.
Upvotes: 3
Views: 2655
Reputation: 68715
yield
does not take or release locks, it simply pauses the current thread execution. So yielding in the synchronized
block will not let the current thread to release lock and let the other methods to enter the synchronized
block. wait/notify
method should be used to release the lock.
From 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.
Upvotes: 4
Reputation: 6121
yield
allows a context switch to other threads, so this thread will not consume the entire CPU usage of the process. The thread still holds the lock. It is the developer responsibility to take care of deadlocks.
Upvotes: 0
Reputation: 451
As far as I know, Yield() only gives up the remaining time slice on the CPU and steps back in the queue. It doesn't release any synchronized objects.
Upvotes: 5