如何在java中作为单独的线程调用and对象的方法?
我试图通过反射调用类对象中的方法。但是,我想将其作为单独的线程运行。有人能告诉我必须对model.java或以下代码进行哪些更改吗如何在java中作为单独的线程调用and对象的方法?,java,multithreading,methods,invoke,Java,Multithreading,Methods,Invoke,我试图通过反射调用类对象中的方法。但是,我想将其作为单独的线程运行。有人能告诉我必须对model.java或以下代码进行哪些更改吗 thread = new Thread ((StatechartModel)model); Method method = model.getClass().getMethod("setVariable",newClass[]{char.class,t.getClass()}); method.invoke(model,'t',t); 您可以执行如下操作,创
thread = new Thread ((StatechartModel)model);
Method method = model.getClass().getMethod("setVariable",newClass[]{char.class,t.getClass()});
method.invoke(model,'t',t);
您可以执行如下操作,创建一个匿名
Runnable
类并在线程中启动它
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();
一旦您的目标对象可用作
最终版
,我建议您使用一个更简单的版本:
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();
启动一个线程并在其中运行您想要运行的方法?可能重复:对我的答案有任何评论吗?如果这对你有帮助,请接受它。