同步代码块

什么情况下需要同步

  • 当多线程并发, 有多段代码同时执行时, 我们希望某一段代码执行的过程中CPU不要切换到其他线程工作. 这时就需要同步.
  • 如果两段代码是同步的, 那么同一时间只能执行一段, 在一段代码没执行结束之前, 不会执行另外一段代码.

作用: 保证了数据的安全性


弊端: 程序的运行效率低


格式:

synchronized(对象) {

    要被同步的代码 ;

}

同步代码块 , 同步方法 , 静态同步方法的锁对象问题:

同步代码块的锁对象是任意对象

同步方法的锁对象为this

静态同步方法的锁对象是该类的字节码文件对象

class Printer {
    Demo d = new Demo();
    public static void print1() {
        synchronized(d){                //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象
            System.out.print("我");
            System.out.print("爱");
            System.out.print("编");
            System.out.print("程");
            System.out.print("!");
            System.out.print("
");
        }
    }

    public static void print2() {   
        synchronized(d){    
            System.out.print("我");
            System.out.print("爱");
            System.out.print("中");
            System.out.print("国");
            System.out.print("
");
        }
    }
}
原文地址:https://www.cnblogs.com/loaderman/p/6411163.html