2011-08-30 106 views
0

下面是代碼,我需要爲2個不同的線程調用2個運行方法,可以這樣做。請幫忙。如何在一個java文件中調用兩個運行方法

public class QuestionList extends ListActivity implements Runnable { 
       //This below thread will call the run method 
     Thread thread = new Thread(QuestionList.this); 
      thread.start(); 

     //can i have one more thread which call run1() method any idea 

} 


public void run() { 


} 

回答

0
public class QuestionList extends ListActivity { 
        //This below thread will call the run method 
      Thread1 thread1 = new Thread(this); 
      thread1.start(); 

      Thread2 thread2 = new Thread(this); 
      thread2.start(); 


    } 

    class Thread1 implements Runnable 
    { 
     public void run() { 


     } 
    } 

    class Thread2 implements Runnable 
    { 
     public void run() { 


     } 
    } 
2

你不能有兩個過程run()方法,我建議不要使用相同的兩個Thread秒(與if()語句來確定適用的行爲)。

相反,您應該創建兩個不同的類(爲什麼不是內部類)來實現這些不同的行爲。喜歡的東西:

public class QuestionList extends ListActivity { 
    class BehaviourA implements Runnable { 
     public void run() { 
     } 
    } 

    class BehaviourB implements Runnable { 
     public void run() { 
     } 
    } 

    private void somewhereElseInTheCode() { 
     BehaviourA anInstanceOfBehaviourA = new BehaviourA(); 
     Thread threadA = new Thread(anInstanceOfBehaviourA); 
     threadA.start(); 

     BehaviourB anInstanceOfBehaviourB = new BehaviourB(); 
     Thread threadB = new Thread(anInstanceOfBehaviourB); 
     threadB.start(); 
    } 
}  

的好處與內部類是,他們可以訪問的QuestionList的成員,這似乎是你願意做的事情。

+0

anInstanceOfBehaviourA你將如何在父線程中爲Thread創建一個子實例threadA = new Thread(anInstanceOfBehaviourA); threadA.start(); – max

+0

我編輯了我的答案以向您展示。另一種方法是讓'類BehaviourA擴展線程'而不是'類BehaviourA實現Runnable'。這樣你創建一個'Thread t = new BehaviourA()',你可以調用't.start();'。這是我在大多數情況下的做法。我使用'implements Runnable'來儘可能地接近你的問題。 – Shlublu

相關問題