简体   繁体   English

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

[英]How to invoke two run methods in one java file

below is the code where i need to invoke 2 run methods for 2 different threads any way this can be done. 下面是我需要为2个不同的线程调用2个run方法的代码,无论如何都可以这样做。 please help on this. 请帮忙。

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


}

You cannot have two run() methods of course, and I suggest not using the same for both Thread s (with a of if() statement to determine which behaviour to apply). 当然,你不能有两个run()方法,我建议不要对两个Thread使用相同的方法(使用if()语句来确定要应用的行为)。

Instead you should create two distinct classes (why not inner classes) to implement these distinct behaviours. 相反,您应该创建两个不同的类(为什么不是内部类)来实现这些不同的行为。 Something like: 就像是:

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

The good thing with inner classes is that they can access to the members of QuestionList , and this seems to be what you are willing to do. 内部类的好处是它们可以访问QuestionList的成员,这似乎是你愿意做的。

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


       } 
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM