Java 如何从主方法定期执行可运行类?
我有一个类Java 如何从主方法定期执行可运行类?,java,multithreading,Java,Multithreading,我有一个类时钟,其代码如下。我想每隔x秒执行时钟中的run方法。但是我希望这是从一个Main方法开始的,而不是从Clock类本身 简单地说,时钟将用于模拟CPU中的时钟单元。每x秒,时钟类的状态将在1和0之间变化,导致程序其余部分的状态发生变化。程序的主要方法将创建一个时钟对象,该对象将在后台定期执行,直到程序终止 我读过关于ScheduledExecutorService的文章,我认为这是理想的,但是它只能用于执行单个可运行对象,而不是整个可运行类 是否存在从位于单独类中的主方法每隔x秒执行一
时钟
,其代码如下。我想每隔x秒执行时钟中的run方法。但是我希望这是从一个Main方法开始的,而不是从Clock类本身
简单地说,时钟将用于模拟CPU中的时钟单元。每x秒,时钟类的状态将在1
和0
之间变化,导致程序其余部分的状态发生变化。程序的主要方法将创建一个时钟对象,该对象将在后台定期执行,直到程序终止
我读过关于ScheduledExecutorService的文章,我认为这是理想的,但是它只能用于执行单个可运行对象,而不是整个可运行类 是否存在从位于单独类中的主方法每隔x秒执行一次时钟类的方法 时钟类
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;
}
}
我想从这里定期执行时钟:
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
}
}
你看过java.util.Timer了吗?这将允许您定期执行TimerTask 您需要更改班级时钟以延长TimerTask
float period = 1.0f;
Clock clockUnit = new Clock(period);
Timer timer = new Timer();
timer.scheduleAtFixedRate(clockUnit, 0, 1000);
你看过java.util.Timer了吗?这将允许您定期执行TimerTask 您需要更改班级时钟以延长TimerTask
float period = 1.0f;
Clock clockUnit = new Clock(period);
Timer timer = new Timer();
timer.scheduleAtFixedRate(clockUnit, 0, 1000);
也许你会发现这很有用:“但是这只能用于执行单个可运行对象,而不是整个可运行类。”-这句话没有意义。也许你会发现这很有用:“但是这只能用于执行单个可运行对象,而不是整个可运行类。”-这句话没有意义。