sychronized and lock and differences

And lock the difference syschronized


synchronized lock reentrant, can not be interrupted, unfair, and Lock reentrant lock, interruptible, be fair, be bound to multiple Condition. (Both can be re-entrant)
synchronized is a key lock is an interface that is class
synchronized unable to obtain income status, are automatic lock, the exception will occur automatically releases the lock
lock state can acquire a lock, manual lock, abnormal does not automatically release to release finally inside to manually
synchronized non-fair is fair lock lock lock
synchronized unavailable interrupting the thread holding the lock has not released, the other can only block waiting time to give up lock can be set to wait

The differences between the ynchronized and Volatile

1) Synchronized ensure visibility and atomic memory operations
2) Volatile memory can only be guaranteed visibility
3) Volatile不需要加锁, more lightweight than Synchronized, and 不会阻塞线程(volatile will not cause obstruction thread; synchronized may cause the thread blocking) synchronized key is to prevent multiple threads to execute a piece of code, it is 会影响程序执行效率, but in some cases the volatile keyword 性能要优于synchronized.
4) is not labeled volatile variable optimizing compiler, and the variable flag may be synchronized optimizing compiler (e.g., compiler optimization discouraged sort)
5) volatile是变量修饰符, while仅能用于变量 synchronized 可用于类方法或代码块的修饰符.

Guess you like

Origin www.cnblogs.com/itcx1213/p/10978023.html