是否在Java中inheritance了同步?

我有超类Point和一个synchronized方法draw() 。 如果我在其中覆盖方法draw()或者我必须总是写它, Point的子类是否会inheritancesynchronized

不,你总是要写synchronized 。 如果你调用超类的synchronized方法,这当然是一个同步调用。 synchronized不是方法签名的一部分。

有关Doug Lea,Java线程老板(或左右)的详细说明,请参见http://gee.cs.oswego.edu/dl/cpj/mechanics.html 。

您可以通过以下方式自行检查:

 public class Shape { protected int sum = 0; public synchronized void add(int x) { sum += x; } } public class Point extends Shape{ public void add(int x) { sum += x; } public int getSum() { return sum; } } 

和测试class

 public class TestShapes { public final static int ITERATIONS = 100000; public static void main(String[] args) throws InterruptedException { final Point p = new Point(); Thread t1 = new Thread(){ @Override public void run() { for(int i=0; i< ITERATIONS; i++){ p.add(1); } } }; Thread t2 = new Thread(){ @Override public void run() { for(int i=0; i< ITERATIONS; i++){ p.add(1); } } }; t1.start(); t2.start(); t1.join(); t2.join(); System.out.println(p.getSum()); // should equal 200000 } } 

在我的机器上它是137099而不是200000。

如果覆盖它并删除同步,不再同步 Overriden方法。 在这里和这里找到它