Hello, I am working on a program, and I noticed that all my threads are starting and stopping in exactly the same order I put them in, and they are not trading places in the output, or mixing output like concurrent objects should. Here is my code:

public class RaceHorseAppII {

    public static void main(String[] args) {
        new RaceHorse("Stan").run();
        new RaceHorse("Tom").run();
        new RaceHorse("Harry").run();
        new RaceHorse("Finn").run();
        new RaceHorse("Sawyer").run();

    }

    public static class RaceHorse implements Runnable {

        private String name = "";

        public RaceHorse(String name){
            this.name = name; 
        }

        public void run() {
            for(int i = 0 ; i < 50 ; i++){
                System.out.println(name);

            }
        }

    }//end inner class

}//end class

Does anyone know why it is doing this?

Ok, so that explains some things, updated code looks like this:

public class RaceHorseAppII {

    public static void main(String[] args) {


        Thread t = new Thread(new RaceHorse("Sawyer"));
        Thread t2 = new Thread(new RaceHorse("Tom"));

        t.start();
        t2.start();

    }

    public static class RaceHorse implements Runnable{

        private String name = "";

        public RaceHorse(String name){
            this.name = name; 
        }

        public void run() {
            for(int i = 0 ; i < 50 ; i++){
                System.out.println(name);

            }
        }

    }//end inner class

}//end class

I still dont know why the output doesn't look something like the following:

Tom
Sawyer
Sawyer
Tom
Sawyer
Tom
Tom
...

It works now! I had another, more complex program I was simultneously working on, and I updated the code with the tweaks I learned about here, and added a few more threads, and I got the alternating action I was looking for. Looks like the less threads you have, the less likely you are to get the altrenating action. Thank you.

Now, how do I mark this solved?

Edited 3 Years Ago by overwraith

This question has already been answered. Start a new discussion instead.