思路就是有一个继承Thread的线程类ProxyThread,这个类接受一个Method对象 ,然后run方法中循环调用它。
测试代码是创建了一个ProxyThread的xianc对象 然后穿了一个fun方法,线程start以后fun之执行一次就结束了。
Threa实现类
package a;
import java.lang.reflect.Method;
public class ProxyThread extends Thread{
private boolean flag;
private Method method;
private Object target;
private Object[]args;
public ProxyThread(boolean flag, Method m, Object target,Object[]args) {
super();
this.flag = flag;
this.method = m;
this.target = target;
}
public void setFlag(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
while(flag) {
try {
method.invoke(target, args);
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
调用代码
package a;
import org.junit.Test;
public class Demo {
@Test
public void test() throws NoSuchMethodException, SecurityException {
ProxyThread thread = new ProxyThread(true,this.getClass().getMethod("fun"),this,null);
thread.start();
}
public void fun() {
System.out.println("=========>");
}
}
思路是传一个Method进去执行
可是fun为什么只执行一次?