如何在一个java文件中调用两个run方法

时间:2011-08-30 09:05:03

标签: java android

下面是我需要为2个不同的线程调用2个run方法的代码,无论如何都可以这样做。请帮忙。

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


}

2 个答案:

答案 0 :(得分:2)

当然,你不能有两个run()方法,我建议不要对两个Thread(使用if()语句使用相同的方法来确定要应用的行为。< / p>

相反,您应该创建两个不同的类(为什么不是内部类)来实现这些不同的行为。类似的东西:

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的成员,这似乎是你愿意做的。

答案 1 :(得分: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() {


       } 
   }