日期:2014-05-20  浏览次数:20658 次

synchronized能不能被继承呢
public class SynchronizationExtends {
public static void main(String args[]) {
Child c = new Child();
Thread t = new Thread(c);
t.start();
c.test2();
}
}

class Father {
int i;
public synchronized void test1() {
i += 100;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}

class Child extends Father implements Runnable{

public synchronized void test2() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}

@Override
public void run() {
this.test1();
}
}
这样打印结果是0,100
但是将父类中方法test1去掉synchronized关键字,打印结果是100,100
这是不是体现锁的互斥性,那为什么说synchronized不能继承呢?

------解决方案--------------------
不需要继承 想多了。
------解决方案--------------------
"那为什么说synchronized不能继承呢?" 
这里所说的不能呢个继承是指,子类覆写了父类的同名方法,父类是加了"synchronized"的,子类默认是没有的. 所以要想要覆写的方法具有"synchronized",需要加上"synchronized".
楼主的程序,test1()没有覆写,所以它是仍是"synchronized"的.