在多线程开发中,我们经常看到synchronized(this)、synchronized(*.class)与synchronized(任意对象)这几种类型同步方法。但是是否知道这几种写法有什么区别了?下面根据代码来分析:
1、synchronized代码块间的同步性
运行结果:
结论:
当一个线程访问ObjectService的一个synchronized (this)同步代码块时,其它线程对同一个ObjectService中其它的synchronized (this)同步代码块的访问将是堵塞,说明synchronized (this)使用的是同一个对象锁。
2、验证synchronized (this)代码块是锁定当前对象
package com.zwz.thread.demo2; public class ObjectService { public void objectMethodA(){ System.out.println("run----objectMethodA"); } public void objectMethodB(){ synchronized (this) { try { for (int i = 1; i <= 10; i++) { System.out.println("synchronized thread name:"+Thread.currentThread().getName()+"-->i="+i); Thread.sleep(1000); } }catch (InterruptedException e) { e.printStackTrace(); } } } }
package com.zwz.thread.demo2; public class ThreadA extends Thread { private ObjectService objectService; public ThreadA(ObjectService objectService) { super(); this.objectService = objectService; } @Override public void run() { super.run(); objectService.objectMethodA(); } }
package com.zwz.thread.demo2; public class ThreadB extends Thread { private ObjectService objectService; public ThreadB(ObjectService objectService) { super(); this.objectService = objectService; } @Override public void run() { super.run(); objectService.objectMethodB(); } }
package com.zwz.thread.demo2; public class MainTest { public static void main(String[] args) throws InterruptedException { ObjectService service=new ObjectService(); ThreadB b=new ThreadB(service); b.start(); Thread.sleep(2000); ThreadA a=new ThreadA(service); a.start(); } }
运行结果: