面试的时候遇到一个问题,继承关系的静态方法是否可以覆写。
根据对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类上面的阻塞队列,排队进入锁块。
如有问题请留言。
相关推荐
java锁机制Synchronized java锁机制Synchronized java锁机制Synchronized java锁机制Synchronized
java中synchronized用法
[JAVA][synchronized的使用]
java中synchronized的使用,java中的锁锁的到底是什么?是括号里的代码块吗?肯定不是的;
java同步synchronized关键字用法示例
java里面synchronized用法
主要介绍了java synchronized同步静态方法和同步非静态方法的异同的相关资料,需要的朋友可以参考下
在学习Java过程中,自己收集了很多的Java的学习资料,分享给大家,有需要的欢迎下载,希望对大家有用,一起学习,一起进步。
java锁机制Synchronized.pdf
java synchronized的一些小实验,对帮助理解synchronized的使用有一定的帮助。
Java中的synchronized:同步方法与线程安全
java锁机制Synchronized[归纳].pdf
如果 再细的分类,synchronized可作用于instance变量、object reference(对象引用)、static函数和class literals(类名称字面常量)身上。 无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而...
主要介绍了基于synchronized修饰静态和非静态方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
synchronized下的方法控制多线程程序中的线程同步非常方便,这里就来看一下Java使用synchronized修饰方法来同步线程的实例演示,需要的朋友可以参考下
java锁机制Synchronized参考.pdf