我正在用Anylogic构建一个简单的智能体基础模型。我想要实现的是智能体的饥饿。代理有一个hunger
参数。我想设置每小时的hunger
+1。我想这应该通过循环来完成,但我不知道如何开始。有人能帮我构建这个循环吗?
发布于 2017-07-19 23:14:02
这是一种解决方案,但是没有考虑完成run()方法所需的时间。
public class HourRun implements Runnable {
private final ScheduledExecutorService scheduler
= Executors.newScheduledThreadPool(1);
int period = 1;
int delay = 0;
TimeUnit timeUnit = TimeUnit.HOURS;
ScheduledFuture scheduledFuture;
public HourRun() {
scheduledFuture = scheduler.scheduleAtFixedRate(this,
period, delay, timeUnit);
}
@Override
public void run() {
// This will be called every hour.
}
}
如果您希望run()方法的结束间隔为一个小时,那么可以在构造函数中使用this。
int initialDelay = 0;
scheduler.scheduleWithFixedDelay(this, initialDelay, delay, timeUnit)
这将在你的run()方法中运行的所有操作和调用之间等待一个小时,然后再次调用它。我不确定这是不是你想要的。也许这样更简单?
new Thread(new Runnable() {
@Override
public void run() {
try {
TimeUnit.HOURS.sleep(1);
} catch (InterruptedException e) {
// Code here
}
}
}).start();
这将在一个独立的线程中运行您想要的任何东西,该线程将在大部分时间处于休眠状态。祝你好运,我希望我能以某种方式帮助你。
发布于 2017-07-19 23:03:33
看看这里的java time api:https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
看看java.time.Duration类,它具有您正在寻找的功能。我不能提供特定的帮助没有一些代码张贴。
https://stackoverflow.com/questions/45194336
复制相似问题