
### synchronized
- ****
- **** static newA synchronized B synchronized ** synchronized synchronized **
- **** synchronized synchronized(this)synchronized static synchronized(class) Class synchronized static synchronized(String a) JVM
synchronized
****
```java
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {
}
public static Singleton getUniqueInstance() {
//
if (uniqueInstance == null) {
//
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
```
uniqueInstance volatile
uniqueInstance volatile uniqueInstance = new Singleton();
1. uniqueInstance
2. uniqueInstance
3. uniqueInstance
JVM 1->3->2 T1 1 3 T2 getUniqueInstance() uniqueInstance uniqueInstance uniqueInstance
volatile JVM
###synchronized
**synchronized JVM **
** synchronized **
```java
public class SynchronizedDemo {
public void method() {
synchronized (this) {
System.out.println("synchronized ");
}
}
}
```
JDK javap SynchronizedDemo `javac SynchronizedDemo.java` .class `javap -c -s -v -l SynchronizedDemo.class`

**synchronized monitorenter monitorexit monitorenter monitorexit ** monitorenter monitor(monitorJavasynchronized Java) .011 monitorexit 0
** synchronized **
```java
public class SynchronizedDemo2 {
public synchronized void method() {
System.out.println("synchronized ");
}
}
```

synchronized monitorenter monitorexit ACC_SYNCHRONIZED JVM ACC_SYNCHRONIZED
Java synchronized monitor Mutex Lock Java synchronized Java 6 Java JVM synchronized synchronized JDK1.6
### JDK1.6
JDK1.6
****
** CAS **
JavaJVM13
** **
(1.6)**CAS** JavaJVM13
** CAS CAS**
** **
/
**/** ****
> ""
JDK1.6 `--XX:+UseSpinning`JDK1.61.6**10`--XX:PreBlockSpin`**
,** JDK1.6 **
** **
** **
### Synchronized ReenTrantLock
** **
10
** synchronized JVM ReenTrantLock API**
synchronized JVM JDK1.6 synchronized ReenTrantLock JDK API lock() unlock try/finally
** ReenTrantLock synchronized **
synchronizedReenTrantLock****
- **ReenTrantLock**lock.lockInterruptibly()
- **ReenTrantLocksynchronized** ReenTrantLock ReenTrantLock`ReentrantLock(boolean fair)`
- synchronizedwait()notify/notifyAll()/ReentrantLockConditionnewCondition() ConditionJDK1.5LockCondition**Condition notify/notifyAll() JVM ReentrantLockCondition** ConditionsynchronizedLockConditionnotifyAll()ConditionsignalAll() Condition
ReenTrantLock
**synchronized ReenTrantLock finally unlock**
** **
JDK1.6synchronized ReenTrantLock synchronized ReenTrantLock synchronized JDK1.6 JVM synchronized **JDK1.6 synchronized ReenTrantLock ReenTrantLock JDK1.6synchronizedReenTrantLocksynchronizedsynchronizedsynchronizedsynchronizedReenTrantLockCAS**