Java多线程赛车模拟问题

时间:2015-10-25 20:56:01

标签: java eclipse multithreading thread-sleep thread-synchronization

我有一个代表赛车的课程,在里面我有一个方法,当汽车通过一个1000 int检查点时,巫婆会打印到控制台。

在运行覆盖中我调用该方法并且它为我创建的每辆车提供不同的运行方式,但我认为我得到了一些错误,因为结果每次都在变化(它需要保持不变,因为有些车更快,所以我不认为汽车在不同的螺纹中移动。)

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();
    }
}}

测试仪(主):

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

2 个答案:

答案 0 :(得分:1)

你应该在循环中移动睡眠,以及在开始线程之前完全创建RacingCars。

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();
    }
}

(请注意,即使您这样做,也没有严格的保证线程被安排运行的顺序。)

答案 1 :(得分:0)

嗯,这里:

public RacingCar(String model, int speed){
    this.start();
    this.model = model;
    this.speed = speed;
}

你在完全创建对象之前使用this.start(),这很糟糕。 第二件事,你在线程运行之后分配参数(意味着非确定性行为)。

通常,您应该创建对象并在构造函数外部运行它。