黑马程序员技术交流社区

标题: synchronized方法能否被继承 [打印本页]

作者: yangshang1    时间: 2012-4-1 11:27
标题: synchronized方法能否被继承
我发现许多地方提及synchronized的关键字不能被继承,但是通过实验发现synchronized的关键字是能够被继承的,是我的实验方式不对?请高手指教,谢谢

import java.text.SimpleDateFormat;
import java.util.Date;

public class TestMain {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
  UtilChild util = new UtilChild();
   
AThread aThread1 = new AThread(util,1);
aThread1.start();
AThread aThread2 = new AThread(util,2);
aThread2.start();
AThread aThread3 = new AThread(util,3);
aThread3.start();
AThread aThread4 = new AThread(util,4);
aThread4.start();
AThread aThread5 = new AThread(util,5);
aThread5.start();
   
}

}

class Util{

public static synchronized void test1(int i){
System.out.println(getDetailDate() + " test1(i), i: " + i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getDetailDate() + " test1(i), i: " + i);
}

public static synchronized void test2(int i){
System.out.println(getDetailDate() + " test2(i), i: " + i);
}

public static void test3(int i){
System.out.println(getDetailDate() + " test3(i), i: " + i);
}

public synchronized void test4(int i){
System.out.println(getDetailDate() + " test4(i), i: " + i);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(getDetailDate() + " test4(i), i: " + i);
}

public synchronized void test5(int i){
System.out.println(getDetailDate() + " test5(i), i: " + i);
}

public static String getDetailDate() {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  return sdf.format(new Date());
  }
}

class UtilChild extends Util{

}

class AThread extends Thread{
UtilChild util = null;
int i = 1;
public AThread(UtilChild util, int i){
this.util = util;
this.i = i;
}

public void run(){
if(this.i== 1){
util.test1(1);
}else if(this.i== 2){
util.test2(2);
}else if(this.i== 3){
util.test3(i);
}else if(this.i== 4){
util.test4(i);
}else if(this.i== 5){
util.test5(i);
}

}
}

运行结果:


2012-03-30 00:40:02 test4(i), i: 4
2012-03-30 00:40:02 test3(i), i: 3
2012-03-30 00:40:02 test1(i), i: 1
2012-03-30 00:40:07 test4(i), i: 4
2012-03-30 00:40:07 test5(i), i: 5
2012-03-30 00:40:07 test1(i), i: 1
2012-03-30 00:40:07 test2(i), i: 2





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2