如何在Java中将和对象的方法作为单独的线程调用? [英] How to call a method of and object as a separate thread in java?
本文介绍了如何在Java中将和对象的方法作为单独的线程调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过反射调用类对象中的方法.但是,我想将其作为单独的线程运行.有人可以告诉我我必须对model.java或以下代码进行的更改吗?
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);
推荐答案
您可以执行以下操作,仅创建一个匿名Runnable
类并在线程中启动它.
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();
这篇关于如何在Java中将和对象的方法作为单独的线程调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文