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?

Output looks like the following:

Stan...
Tom...
Harry...
Finn...
Sawyer...

Callling run executes those methods on the current thread. You need the Thread class and its start method.

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
...

That code looks OK. You start two threads, you expect two printlns.

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?

Button at the bottom left of this screen labelled "Mark Question Solved"

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.