JAVA静态方法synchronized锁定类

面试的时候遇到一个问题,继承关系的静态方法是否可以覆写。

根据对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类上面的阻塞队列,排队进入锁块。

 

如有问题请留言。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值