A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yangshang1 中级黑马   /  2012-4-1 11:27  /  1511 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

我发现许多地方提及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

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马