概念
happens-before:A先行于B发生,并且能查看A的修改结果。
重入同步:即持有锁,调用其它含有该锁的方法时,持有当前锁即可访问。
voliate:易变得,每次修改,在另一个线程即可见修改结果。
syncronized:加锁。分为:类锁,对象锁
使用格式
1.代码块加锁
1)变量(锁的属性对象)
synchronized(variable){
}
2)this(当前对象)
synchronized(this){
}
3)类.class(类)
synchronized(A.class){
}
2.方法加锁
1)给普通方法加锁,锁定当前对象
public synchronized void method(){}
2)给静态方法加锁,锁定当前类
public static synchronized void method(){}
代码
public class SynCount {
private static Object lock = new Object();
private static Integer count = 0;
//给对象加锁
public void synBlockObject(){
synchronized (this) {
count++;
}
}
//给lock属性对象加锁
public void synBlockVar(){
synchronized (lock) {
count++;
}
}
//给类加锁
public void synBlockClass(){
synchronized (SynCount.class) {
count++;
}
}
//给对象加锁
public synchronized void synMethod(){
count++;
}
//给类加锁
public synchronized static void synStaticMethod() {
count++;
}
}
public class Test {
private static Integer size = 20000;
public static void main(String[] args) {
SynCount synCount = new SynCount();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i =0;i<size;i++) {
//1.验证加锁是否成功
// synCount.synBlockObject();
//2.验证块对象加锁和方法加锁一致
// synCount.synBlockObject();
//3.验证块变量加锁是否成功。锁的是变量对象。
// synCount.synBlockVar();
// synCount.synBlockVar();
//4.验证类加锁
synCount.synBlockClass();
}
synCount.getCount();
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i =0;i<size;i++) {
//1.
// synCount.synBlockObject();
//2
// synCount.synMethod();
//3.
// synCount.synBlockVar();
// synCount.synMethod();
//4.
synCount.synStaticMethod();
}
synCount.getCount();
}
});
t1.start();
t2.start();
}