什么情况下需要同步
作用: 保证了数据的安全性
弊端: 程序的运行效率低
格式:
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("\r\n"); } } public static void print2() { synchronized(d){ System.out.print("我"); System.out.print("爱"); System.out.print("中"); System.out.print("国"); System.out.print("\r\n"); } } }
原文:http://www.cnblogs.com/loaderman/p/6411163.html