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. please help on this.
public class QuestionList extends ListActivity implements Runnable {
//This below thread will call the run method
Thread thread = new Thread(Quest开发者_JS百科ionList.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).
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.
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() {
}
}
精彩评论