JAVA的synchronized写法

使用关键字synchronized的写法比较多,常用的有如下几种,代码如下:

public class MyService
{
     synchronized public static void testMethod1()
     {
     }
     public void testMethod2()
    {
         synchronized(MyService.class)
         {
         }
     }
  
     synchronized public void testMethod3()
    {
     }
  
     public void testMethod4()
    {
         synchronized(this)
     {
     }
     }  
 
     public void testMethod5()
     {
        synchronized("abc") {}
     }
 
}

 

上面的代码中出现了3中类型的锁对象:

(A) testMethod1() 和testMethod2()持有的锁是同一个, 即MyService.java对应Class类的对象。

(B) testMethod3()和testMethod4()持有的锁是同一个,即MyService.java类的对象。

 (C) testMethod5()持有的锁是字符串abc。

说明 testMethod1() 和testMethod2()是同步关系,testMethod3()和testMethod4()是同步关系,A和C之间是异步关系,B和C之间是异步关系,A和B之间是异步关系。

posted @ 2020-04-23 16:08  Sunshine106  阅读(263)  评论(0编辑  收藏  举报