简体   繁体   English

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

[英]How to call a method of and object as a separate thread in 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? 有人能告诉我我必须在model.java或代码下面做出的更改吗?

 thread = new Thread ((StatechartModel)model);
 Method method = model.getClass().getMethod("setVariable",newClass[]{char.class,t.getClass()});
 method.invoke(model,'t',t);

You could do something like the following which just creates an anonymous Runnable class and starts it in a thread. 您可以执行以下操作,只创建一个匿名的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();

Let me suggest a simpler version once you have your target object available as a final : 一旦您将目标对象作为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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM