2012-03-01 25 views
0

我想通過反射調用類對象中的方法。但是,我想將它作爲單獨的線程運行。有人能告訴我我必須對model.java或下面的代碼進行更改嗎?如何在java中調用一個方法和對象作爲一個單獨的線程?

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

啓動一個線程,並在其中運行要運行的方法? – 2012-03-01 13:41:24

+0

可能的重複:http://stackoverflow.com/questions/3489543/how-to-call-a-method-with-a-separate-thread-in-java – Gray 2012-03-01 13:43:56

+0

對我的答案有任何意見?如果它幫助你,請接受它。 – Gray 2012-03-15 21:30:34

回答

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(); 
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(); 
相關問題