有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

下面是我需要为两个不同的线程调用两个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() {


}

共 (1) 个答案

  1. # 1 楼答案

    当然,您不能有两个run()方法,我建议不要对两个Thread都使用相同的方法(使用of 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的成员,这似乎是您愿意做的事情