2015-09-13 68 views
0

我有兩個類如何同步父類的嵌套Java類方法?

public class A { 
    private byte[] buf; 
    public synchronized void foo() { 
     // does something with buf 
    } 
    public class B { 
     public synchronized void bar() { 
      // also does something with buf 
     } 
    } 
} 

據我所知,方法bar()B類的一個實例同步。我如何在類A的對象上同步它以保護buf

回答

1

正如所解釋的in this answer,你可以做到以下幾點:

public class A { 
    private byte[] buf; 

    public synchronized void foo() { 
     // does something with buf 
    } 

    public class B { 
     public void bar() { 
      synchronized (A.this) { 
       // also does something with buf 
      } 
     } 
    } 
} 

這種方法只適用的,因爲你使用了它的父類的引用嵌套類。但是,如果你只想同步變量buf的用法,你也可以這樣做:

public class A { 
    private byte[] buf; 

    public void foo() { 
     synchronized (buf) { 
      // does something with buf 
     } 
    } 

    public class B { 
     public void bar() { 
      synchronized (buf) { 
       // also does something with buf 
      } 
     } 
    } 
} 
+0

'synchronized(A.this)'是我所需要的。謝謝! – Antonio