问题
I am trying to invoke a method in a class object via reflection. However, I want to run it as separate thread. Can someone tell me the changes I have to make on model.java or below code?
thread = new Thread ((StatechartModel)model);
Method method = model.getClass().getMethod("setVariable",newClass[]{char.class,t.getClass()});
method.invoke(model,'t',t);
回答1:
You could do something like the following which just creates an anonymous Runnable class and starts it in a thread.
final Method method = model.getClass().getMethod(
"setVariable", newClass[] { char.class, t.getClass() });
Thread thread = new Thread(new Runnable() {
public void run() {
try {
// NOTE: model and t need to defined final outside of the thread
method.invoke(model, 't', t);
} catch (Exception e) {
// log or print exception here
}
}
});
thread.start();
回答2:
Let me suggest a simpler version once you have your target object available as a final:
final MyTarget finalTarget = target;
Thread t = new Thread(new Runnable() {
public void run() {
finalTarget.methodToRun(); // make sure you catch here all exceptions thrown by methodToRun(), if any
}
});
t.start();
来源:https://stackoverflow.com/questions/9516994/how-to-call-a-method-of-and-object-as-a-separate-thread-in-java