【Java】java多线程使用反射向多线程传入方法示例

1.TestThread.java

import java.lang.reflect.Method;

public class TestThread {
    public static String variables = "variables";

    public static void main(String args[]) throws NoSuchMethodException {
        //反射机制
        Method method1 = TestThread.class.getMethod("method1", String.class);
        ThreadDemo2 R1 = new ThreadDemo2("Thread-1", method1, new TestThread(), "message1 parama");
        R1.start();

        Method method2 = TestThread.class.getMethod("method2", String.class);
        ThreadDemo2 R2 = new ThreadDemo2("Thread-2", method2, new TestThread(), "message2 parama");
        R2.start();
    }

    public static void method1(String message) {
        System.out.println(message);
        //variables为static,method1中修改method2也能感知到
        TestThread.variables = "method1修改variables";
        System.out.println("method1中variables值:" + TestThread.variables);

    }

    public static void method2(String message) {
        System.out.println(message);
        //variables为static,method1中修改method2也能感知到
        System.out.println("method2中variables值:" + TestThread.variables);
    }

}

 

2.ThreadDemo2.java

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

class ThreadDemo2 extends Thread {
    private Thread t;
    private String threadName;
    private Method method;
    private TestThread testThread;
    private String path;

    ThreadDemo2(String name, Method method, TestThread testThread, String path) {
        threadName = name;
        System.out.println("Creating " + threadName);
        this.method = method;
        this.testThread = testThread;
        this.path = path;
    }

    public void run() {
        Object[] parameters = new Object[1];
        parameters[0] = this.path;
        System.out.println("Running " + threadName);
        try {
            this.method.invoke(this.testThread, parameters);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println("Thread " + threadName + " exiting.");
    }

    public void start() {
        System.out.println("Starting " + threadName);
        if (t == null) {
            t = new Thread(this, threadName);
            t.start();
        }
    }
}

3.执行结果

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Running Thread-2
message1 parama
message2 parama
method1中variables值:method1修改variables
method2中variables值:method1修改variables
Thread Thread-1 exiting.
Thread Thread-2 exiting.

 

posted @ 2021-12-17 10:01  vickylinj  阅读(214)  评论(0编辑  收藏  举报