Java——》synchronized的使用

推荐链接:
    总结——》【Java】
    总结——》【Mysql】
    总结——》【Redis】
    总结——》【Kafka】
    总结——》【Spring】
    总结——》【SpringBoot】
    总结——》【MyBatis、MyBatis-Plus】
    总结——》【Linux】
    总结——》【MongoDB】
    总结——》【Elasticsearch】

Java——》synchronized的使用

synchronized是互斥锁,锁是基于对象实现的,每个线程基于synchronized绑定的对象去获取锁!

有明确指定锁对象:

  • synchronized(变量名):当前变量做为锁
  • synchroinzed(this):this做为锁

无明确指定锁对象同步方法同步代码块

  • 有static修饰:当前类.class做为锁(类锁
  • 无static修饰:当前对象做为锁(对象锁
public class MiTest {

    public static void main(String[] args) {
        // 锁的是当前Test.class
        Test.a();

        Test test = new Test();
        // 锁的是new出来的test对象
        test.b();
    }

}

class Test{
    public static synchronized void a(){
        System.out.println("1111");
    }

    public synchronized void b(){
        System.out.println("2222");
    }
}

你可能感兴趣的:(Java,java,synchronized)