关于JAVA 多线程 与 反射的问题

思路就是有一个继承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为什么只执行一次?

start这样启动的是守护线程,当主线程完成时,程序自动退出。在thread.start();后面加上 System.in.read();或者 Thread.sleep(30000);即可输出。

看看是不是主线程退出了,没有执行下去

主线程挂起,异步执行,Thread.currentThread().wait();

这个是junit.Test问题,你改成 public static void main(String []argv) {
Demo demo=new Demo();
ProxyThread thread;
try {
thread = new ProxyThread(true,demo.getClass().getMethod("fun"),demo,null);
thread.start();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

} 

    执行结果 就是
    =========>

=========>
=========>
=========>
=========>
=========>
=========>
=========>无限打印了

正常输出图片说明
加上 System.in.read(); 等待用户输入就终止
或者用 Thread.sleep(30000);等30秒.

在thread.start()后面添加thread.join(),让主线程等待子线程执行完毕后再执行。否则,主线程执行退出,子线程也就关闭了。