我如何在线程上重载run方法

时间:2019-01-30 14:47:33

标签: java multithreading parameters

我目前正在一个项目中,我需要模拟停车场中的交通。我在单独的线程中运行模拟器。

当我使用以下命令启动线程时:

Thread simulatorThread = new Thread(simulator);
simulatorThread.start();

这将激活Simulator类上的run方法。 在这种运行方法中,定义了模拟器将运行10000滴答声。 我希望能够使用参数手动重载该运行方法,因此我可以运行X个刻度。 但是因为run方法是使用start()方法执行的,所以我无法将任何参数传递给它。 我知道我可以通过构造函数来实现,但这意味着它只能

run(200);

一次,然后需要再次启动该线程。 我想知道是否有可能先启动线程,然后

run(200)

然后在同一线程中

run(400);

据我所知,这不可能通过构造函数来实现,这暗示了锁定我的帖子的人。

我们将不胜感激。

我试图在start()方法中放置一个参数,但这不起作用。

@FXML
void startSimulation(ActionEvent event) {
    if (!simIsRunning){
        try{
            simulator = new Simulator(
                    simulatorAnchorPane,
                    dailyIncomeValue,
                    missedIncomeValue,
                    totalQueueSizeValue
            );
            simulatorThread = new Thread(simulator);
            simulatorThread.start();
            simIsRunning = true;
        }
        catch(Exception e){

        }
    }else{
        stopSimulation();
    }
}

在模拟器中:

public void run() {
    for (int i = 0; i < 10000; i++) {
        tick();
    }
}

public void run(int numTicks) {
    for (int i = 0; i < numTicks; i++) {
        // dit is de overloaded functie om de stappen te bepalen
        tick();
    }
}

0 个答案:

没有答案