简体   繁体   English

如何定期从main方法执行可运行类?

[英]How do I periodically execute a runnable class from a main method?

I have a class Clock , the code for which is below. 我有一个Clock类,其代码如下。 I want to execute the run method found in Clock every x amount of seconds. 我想每隔x秒钟执行一次在Clock中找到的run方法。 But I want this to be initiated from a Main method, not from the Clock class itself. 但是我希望这是从Main方法而不是Clock类本身启动的。

To put it simply, Clock will be used to simulate a clock unit found in a CPU. 简而言之,时钟将用于模拟CPU中找到的时钟单元。 Every x amount of seconds, the state of the Clock class will change between a 1 and a 0 , causing the state of the rest of the program to change. 每x秒,Clock类的状态将在10之间变化,从而导致程序其余部分的状态发生变化。 The Main method of the program will create a Clock object and this will execute periodically in the background until the program is terminated. 程序的Main方法将创建一个Clock对象,该对象将在后台定期执行,直到程序终止。

I've read about the ScheduledExecutorService and I thought this would be ideal, however this can only be used to execute a single runnable object, not an entire runnable class. 我已经阅读了ScheduledExecutorService ,我认为这是理想的选择,但是它只能用于执行单个可运行对象,而不是整个可运行类。

Is there anyway to execute my Clock class every x amount of seconds from a Main method located in a separate class? 无论如何,是否可以从位于单独类中的Main方法每x秒执行我的Clock类?

Clock class 时钟类

public class Clock implements Runnable{

    private int state = 0; //the state of the simulation, instrutions will execute on the rising edge;
    private float executionSpeed; //in Hz (executions per second)

    private String threadName = "Clock";

    public Clock(float exeSpeed)
    {
        executionSpeed = exeSpeed;
        System.out.println("[Clock] Execution speed set to " + executionSpeed + "Hz. (" + (1/executionSpeed) + " instructions per second.)");
    }

    public void run()
    {
        System.out.println(threadName + " executed.");
        toggleState();
    }

    public void toggleState()
    {
        if(state == 1)
        {
            state = 0;
        }
        else if(state == 0)
        {
            state = 1;
        }
    }

    public float getExecutionSpeed()
    {
        return executionSpeed;
    }

}

I want to periodically execute Clock from here: 我想从这里定期执行Clock:

public class Main {

    public static void main(String[] args)
    {
        float period = 1.0;
        Clock clockUnit = new Clock(period);

        //execute clock.run() every 1.0 seconds
    }
}

Did you look at java.util.Timer? 您看过java.util.Timer吗? This will allow you to exectute a TimerTask periodically. 这将允许您定期执行TimerTask。

You will need to change your class Clock to extend TimerTask. 您将需要更改Clock类以扩展TimerTask。

float period = 1.0f;
Clock clockUnit = new Clock(period);
Timer timer = new Timer();
timer.scheduleAtFixedRate(clockUnit, 0, 1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM