如何在java中将方法和对象作为单独的线程调用?

时间:2012-03-01 13:23:01

标签: 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);

2 个答案:

答案 0 :(得分:2)

您可以执行以下操作,只创建匿名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();

答案 1 :(得分:0)

一旦您将目标对象作为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();