面试的时候遇到一个问题,继承关系的静态方法是否可以覆写。
根据对JAVA语言的了解,静态方法是和类绑定的,因此不存在覆写,在运行时,继承关系应该是针对对象的,而不是类的。
具体的方式参考http://phl.iteye.com/blog/2029729
在这儿写一下多线程访问的时候锁定的状况。
public class child extends father {
public synchronized static String call() throws InterruptedException {
System.out.println("this is in child");
Thread.sleep(10000);
return "child";
}
}
public class father {
public synchronized static String call() throws InterruptedException{
System.out.println("this is in father");
Thread.sleep(10000);
return "father";
}
}
public class extendTest implements Callable<String> {
private CountDownLatch begin;
public extendTest(CountDownLatch begin) {
this.begin = begin;
}
@Override
public String call() throws Exception {
try {
begin.await();
Random r = new Random();
if (r.nextBoolean()) {
return child.call();
} else {
return father.call();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void main(String args[]) throws InterruptedException, ExecutionException {
CountDownLatch begin = new CountDownLatch(1);
ExecutorService es = Executors.newFixedThreadPool(10);
List<Future<String>> result = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
extendTest et = new extendTest(begin);
Future<String> r = es.submit(et);
result.add(r);
}
begin.countDown();
es.shutdown();
for (Future<String> fs : result) {
System.out.println(fs.get());
}
}
}
输出结果:
this is in child
this is in father
//停顿
this is in child
this is in father
//停顿
this is in child
child
child
father
this is in father
this is in child
father
this is in father
child
this is in child
child
father
this is in father
father
child
father
数据的返回结果说明形成了是一个在father类和child类上面的阻塞队列,排队进入锁块。
如有问题请留言。