【问题标题】:How to call a method of and object as a separate thread in java?如何在java中将方法和对象作为单独的线程调用?
【发布时间】:2012-03-19 23:51:17
【问题描述】:

我正在尝试通过反射调用类对象中的方法。但是,我想将它作为单独的线程运行。有人可以告诉我必须对 model.java 或以下代码进行哪些更改吗?

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

【问题讨论】:

标签: java multithreading methods invoke


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 2015-01-21
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多