一、修饰方法
1.修饰普通方法
① synchronized方法 VS 非synchronized方法
public void method() { System.out.println("run method"); try { Thread.sleep(2000); } catch (InterruptedException e) { } System.out.println("end method"); } public synchronized void generalMethod() { System.out.println("run general"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end general"); } 运行结果: run method run general end method end general
小结:synchronized修饰的方法与其它非synchronized修饰的方法同时调用不相互影响
2.修饰静态方法
① 静态synchronized方法 VS synchronized方法
public synchronized void generalMethod() { System.out.println("run general"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end general"); } public synchronized static void staticMethod() { System.out.println("run static"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end static"); } 运行结果: run general run static end general end static
小结:静态synchronized方法与synchronized方法同时调用不会阻塞
二、修饰代码块
1.同步对象为class
① 同步对象为class VS 同步对象为对象
public void objectMethod() { synchronized (this) { System.out.println("run object"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end object"); } } public void classMethod() { synchronized (SynchronizedTest.class) { System.out.println("run class"); } try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end class"); } 运行结果: run object run class end class end object
小结:调用同步对象为class代码块与调用同步对象为对象的代码块不会阻塞
② 同步对象为class VS 静态synchronized方法
public synchronized static void staticMethod() { System.out.println("run static"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end static"); } public void classMethod() { synchronized (SynchronizedTest.class) { System.out.println("run class"); } try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end class"); } 运行结果: run static end static run class end class
小结:调用同步对象为class代码块与静态synchronized方法同时调用会阻塞
2.同步对象为对象
① 同步对象为class VS 同步对象为对象
public void classMethod() { synchronized (SynchronizedTest.class) { System.out.println("run class"); } try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end class"); } public void objectMethod() { synchronized (this) { System.out.println("run object"); try { Thread.sleep(5000); } catch (InterruptedException e) { } System.out.println("end object"); } } 运行结果: run class run object end class end object
结论:
静态方法属于类,同步静态方法的锁是加在类上;普通方法属于对象,同步非静态方法的锁是加在那个对象上;锁的对象不一样就不会阻塞,代码块同理。