1

I am a beginner here and started learning java programming.

I wrote a program to try threading. In one class i wrote a program to display numbers from one to 100 and in another class to display number from 999 to 100. Now in the the main i have created an object reference for both the class(r1,r2)) and created a object for thread and passed(r1,r2-object reference of my class) them as a parameter. Now the output i get is not as expected in some way i feel my second thread is not getting executed. I am not sure if there is anything wrong with my logic or the program. Any help/advice would be appreciated. My code below for reference.

Class 1:

public class Run implements Runnable {

@Override
public void run() {

    for (int i = 0; i < 100; i++) {
        try {

            Thread.sleep(200);
        } catch (InterruptedException ex) {
            Logger.getLogger(Run.class.getName()).log(Level.SEVERE, "...", ex);
        }
        System.out.println(i);
    }
}
}

Class 2: public class Run2 extends Thread {

public void run2() {

    for(int i=999;i>0;i--){
        try {

            Thread.sleep(500);
        } catch (InterruptedException ex) {
            Logger.getLogger(Run2.class.getName()).log(Level.SEVERE, "....", ex);
        }
        System.out.println(i);


    }

}
} 

Main class:

public class Threading {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    Run r= new Run();
    Thread t1=new Thread(r);
     t1.start();

    Run2 r2=new Run2();
    Thread t2=new Thread(r2);

    t2.start();


}

}

2 Answers 2

5

Rename Run2's method run2 to run. You're subclassing Thread, so you get a run method that doesn't do anything (actually it checks to see if it was passed in a target runnable, in which case it calls run on the target, but since the target is null it does nothing), and that's what's getting run.

Make a habit of implementing Runnable instead of extending Thread, and use the @Override annotation to catch mistakes where you think you're overriding something but you're not.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2271636: np, it's a really easy mistake to make. hope this helps.
2

Your class Run2's method should be named run and not run2.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.