请求响应一个线程中N个方法时,每隔5s,向前台推送当前执行哪个方法(未执行方法覆盖掉已执行方法名称存在一个变量中)。
package com.synnex.just.test;
public class SomeMethod {
private String currentMethodName;
public void m1(){
setCurrentMethodName("m1");
System.out.println("m1 executing .....");
}
public void m2(){
setCurrentMethodName("m2");
System.out.println("m2 executing .....");
}
public void m3(){
setCurrentMethodName("m3");
System.out.println("m3 executing .....");
}
public void m4(){
setCurrentMethodName("m4");
System.out.println("m4 executing .....");
}
public String getCurrentMethodName() {
return currentMethodName;
}
public void setCurrentMethodName(String currentMethodName) {
this.currentMethodName = currentMethodName;
}
}
--------------------------------------------------------------------------------------------------------------------------------
package com.synnex.just.test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class SomeThread extends Thread {
private SomeMethod m ;
public SomeThread(SomeMethod m){
this.m=m;
}
@Override
public void run() {
Class> classz=null;
try {
classz = Class.forName("com.synnex.just.test.SomeMethod");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method[] declaredMethods = classz.getDeclaredMethods();
while(true){
for(Method method : declaredMethods){
if(!method.getName().startsWith("m")){
continue;
}
try {
Thread.currentThread().sleep(2000);
method.invoke(m, null);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
-----------------------------------------------------------------------------------------------------------------------------
package com.synnex.just.test;
public class Main {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
SomeMethod m = new SomeMethod();
SomeThread t = new SomeThread(m);
t.start();
while(true){
Thread.sleep(5000);
System.out.println("Current method"+m.getCurrentMethodName());
}
}
}