Search code examples
javaeclipsemultithreadingthread-sleepthread-synchronization

Java Multi-Thread racing simulation issue


I have a class which represents the racing car and inside of it i have a method witch prints to the console whenever a car passes a 1000 int checkpoint.

inside the run override i call that method and it suppoused to run differently for each car i create, but i think i got something wrong because the results changes every time(it needs to stay the same because some cars are faster, so i dont think the cars are moving in different threads).

public class RacingCar extends Thread{
private String model;
private int speed;
public RacingCar(){}
public RacingCar(String model, int speed){
    this.start();
    this.model = model;
    this.speed = speed;
}
public void go(){
    int trackLength=5000;
    int checkPointPassed=0;
    for(int i=0;i<trackLength;i+=speed){
        if(checkPointPassed*1000<i){
            checkPointPassed++;
            System.out.println(this.model+" has passed the "+checkPointPassed+"th check point");
        }
    }
}
@Override
public void run() {
    go();
    try {
        Thread.sleep(10);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}}

Tester(main):

public class Tester {
public static void main(String[] args) {
    new RacingCar("Honda", 6);
    new RacingCar("Lamborghini", 100);
    new RacingCar("McLaren", 8);
}}

Solution

  • You should move the sleep inside the loop, as well as fully creating the RacingCars before starting the threads.

    public class RacingCar extends Thread {
        private String model;
        private int speed;
    
        public RacingCar(String model, int speed) {
            this.model = model;
            this.speed = speed;
        }
    
        @Override
        public void run() {
            try {
                go();
            } catch(InterruptedException e) {
                e.printStackTrace();
            }
        }
    
        private void go() throws InterruptedException {
            int trackLength = 5000;
            int checkPointPassed = 0;
            for(int i = 0; i < trackLength; i += speed) {
                if(checkPointPassed * 1000 < i) {
                    checkPointPassed++;
                    System.out.println(this.model + " has passed the " + checkPointPassed + "th check point");
                }
                Thread.sleep(10);
            }
        }
    }
    
    public class Tester {
        public static void main(String[] args) {
            RacingCar honda = new RacingCar("Honda", 6);
            RacingCar lamborghini = new RacingCar("Lamborghini", 100);
            RacingCar mcLaren = new RacingCar("McLaren", 8);
    
            honda.start();
            lamborghini.start();
            mcLaren.start();
        }
    }
    

    (Mind that even when you do this, you have no strict guarantee in which order the threads are scheduled to run.)