问题
As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.
On
synchronizedwithout usingwait(), Does a thread state set toBLOCKED?Does a thread in
BLOCKED&WAITINGstate consume CPU cycles?
回答1:
As mentioned in answer, synchronized is implemented using compareAndSwap, which is non-blocking algorithm.
I think you are misreading that answer. synchronized is certainly not implemented with the Java-level compareAndSwap call. It will be implemented in native code by the interpreter and JIT in your JVM. Under the covers it might use the compare-and-swap instruction, or it may use something else (atomic test-and-set and atomic exchange are also common - and some platforms don't even have a CAS primitive).
This is definitely not a "non-blocking algorithm" - by definition synchronized implements a type of critical section which implies blocking if a second thread tries to enter the critical section while another thread is inside it.
1) On synchronized without using wait(), Does a thread state set to BLOCKED?
Yes, if a thread is waiting to enter a synchronized section, its state is set to BLOCKED.
2) Does a thread in BLOCKED & WAITING state consume CPU cycles?
Generally no, at least not in an ongoing manner. There is a CPU cost associated with entering and exiting the state1, but once the thread is blocked it is generally held in a non-runnable state until it is awoken when the monitor becomes free, and doesn't use CPU resources during that time.
1 Which is exactly why good implementations will generally "spin" a bit before going to sleep, in case the critical section is short and the holding thread may soon exit - spinning in this case avoids the 1000+ cycle overhead of making the transition to sleep (which involves the OS, etc).
来源:https://stackoverflow.com/questions/47851595/mutual-exclusion-how-synchronized-works