How to call a method of and object as a separate thread in java?

。_饼干妹妹 提交于 2019-12-08 10:13:55

问题


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);

回答1:


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();



回答2:


Let me suggest a simpler version once you have your target object available as a 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();


来源:https://stackoverflow.com/questions/9516994/how-to-call-a-method-of-and-object-as-a-separate-thread-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!