Search code examples
javamultithreadingconcurrencyrunnable

How do I make concurrently running threads?


I want to have two separate threads running two different instances of different classes and I want them to execute the run command at the same time.

I've made a practice class to demonstrate the problem I'm having. One racer counts forwards, the other counts backwards.

public class testCount {

    public static void main(String args[]) {
        testCount countCompetition = new testCount();
        countCompetition.run();
    }

    public void run() {
        (new Thread(new racer1())).start();
        (new Thread(new racer2())).start();
    }

    public class racer1 implements Runnable {
        public void run() {
            for(int x = 0; x < 100; x++) {
                System.out.println(x);
            }
        }
    }
    public class racer2 implements Runnable {
        public void run() {
            for(int y = 100; y > 0; y--) {
                System.out.println(y);
            }
        }
    }
}

My results

1
2
... All the way to 100
100
100
99
... All the way back down
1

What I want

1
100
2
99
3
98

They don't need to be taking turns like that, but they do need to be working at the same time, instead of one after the other. Any hints, advice or code snippets would be greatly appreciated.


Solution

  • Just add Thread.sleep(1); in each racer class after System.out.println().

    i.e. it will look like this:

    public class racer1 implements Runnable {
        public void run() {
            for(int x = 0; x < 100; x++) {
                System.out.println(x);
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }