代码如下:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
public class Test {
public static void main(String args[]){
Aaa aaa = new Aaa(“ddd”);
Thread t1 = new Thread(aaa);
t1.start();
aaa.ccc();
}
}
class Aaa implements Runnable{
private static final long serialVersionUID = 1L;
private static Date maindate = new Date();
private static String name;
public Aaa(String str){
name = str;
}
public void setName(String changeName){
log(“————“+changeName);
name = changeName;
}
public void run(){
try {
Thread.sleep(1);
Method method = this.getClass().getMethod(name, null);
if(method != null){
method.invoke(this, null);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public synchronized void aaa(){
log(“aaa 进入方法 “+name);
try{
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
}
log(“aaa 退出方法 “+name);
}
public void bbb(){
log(“bbb 进入方法 “+name);
synchronized(this){
log(“bbb 进入同步 “+name);
try{
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
}
log(“bbb 退出方法 “+name);
}
}
synchronized
public void ccc(){
log(“ccc 进入方法 “+name);
try{
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
}
log(“ccc 退出方法 “+name);
}
public static synchronized void ddd(){
log(“ddd 进入方法 “);
try{
Thread.sleep(5000);
}catch(Exception e){
e.printStackTrace();
}
log(“ddd 退出方法 “);
}
private static void log(String str){
Date date = new Date();
if(date.getTime()-maindate.getTime()>500){
System.out.println(“——————————————–“);
}
maindate = date;
System.out.println(“[“+date.getTime()+”]”+str);
}
}



