Synchronized
为啥要用锁?线程安全问题:1.存在共享数据 ;2.多线程共同操作共享数据。
public class T{
private int count = 0;
private Object o = new Object();
public void method(){
synchronized(o){
//任何线程执行下面的代码都需要先获取o的锁
count--;
System.out.println(Thread.currentThread().getName()+" count: "+count);
}
}
}
Java的对象头如上图,synchronized主要是在通过lock的两位进行锁状态的标记。如下:
biased_lock | lock | 状态 |
---|---|---|
0 | 01 | 无锁 |
1 | 01 | 偏向锁 |
0 | 00 | 轻量级锁 |
0 | 10 | 重量级锁 |
0 | 11 | GC标记 |
synchronized(this)和 synchronized方法
public class T{
public synchronized void method(){
//等同于在方法的执行部分添加synchronized(this)
count--;
System.out.println(Thread.currentThread().getName()+" count: "+count);
}
}
synchronized(T.class)和 synchronized静态方法
public class T{
public synchronized static void method(){
//等同于在方法的执行部分添加synchronized(T.class)
count--;
System.out.println(Thread