关于Syncronized继承问题 public class Widget{public syncronized void doSomething(){}}public class LoggingWidget extends Widget(){public syncronized void doSomething(){}}问题:如果调用LoggingWidget中的doSomething()方法,是获得LoggingWidget对象的锁还是其父类Widget对象的锁还是两者的锁都要获得? 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 synchronized关键字是不能继承的,也就是说,基类的方法synchronized f(){} 在继承类中并不自动是synchronized f(){},而是变成了f(){}。继承类需要你显式的指定它的某个方法为synchronized方法http://www.diybl.com/course/3_program/java/javajs/20090916/175548.html 判断锁的对象很简单,静态方法中的是synchronized(class),就是在该方法所在类的class对象上加锁非静态方法就是synchronized(this),在调用它的对象上加锁 class T1 { public synchronized void test() { System.out.println("T1"); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("T1 over"); }}class T2 extends T1 implements Runnable { public static void main(String... args) { T2 t2 = new T2(0); new Thread(t2).start(); new Thread(t2).start(); } private int i = 0; public T2(int i) { this.i = i; } public void run() { if (i++ % 2 == 0) super.test(); else test(); } public void setI(int j) { this.i = j; } public synchronized void test() { System.out.println("T2"); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("T2 over"); }}看结果是2个锁。 应该还是1个锁,只不过这2个方法都合并在了子类的方法表上了。所以super调用的时候对象和不使用super时候的锁对象是一样的。 创建LoggingWidget对象的时候,就是创建了一个LoggingWidget 对象,不存在所谓的“父类对象”,jvm在每个对象的对象头位置创建一个与锁有关的位段。 spring+hibernate整合报错 java虚拟机性能问题 希望高手急救=》Jgraph如何在edge上添加标签。 String s= new String("hello")的老问题。。。 为什么输出是"空"(null) 求助一个float类型的问题 初学者的困惑?????????? package的定义 咳,要考人工智能了? 难为大侠J++ 告诉我Undefined package 'lang' ?? 为 关于异常处理,try{}catch{}finally{}与try{} finally{}的区别? 帮忙,java如何实现udp穿越nat
http://www.diybl.com/course/3_program/java/javajs/20090916/175548.html
非静态方法就是synchronized(this),在调用它的对象上加锁
public synchronized void test() {
System.out.println("T1");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("T1 over");
}
}class T2 extends T1 implements Runnable { public static void main(String... args) {
T2 t2 = new T2(0);
new Thread(t2).start();
new Thread(t2).start(); } private int i = 0; public T2(int i) {
this.i = i;
} public void run() {
if (i++ % 2 == 0)
super.test();
else
test();
} public void setI(int j) {
this.i = j;
} public synchronized void test() {
System.out.println("T2");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("T2 over");
}
}
看结果是2个锁。