【问题标题】:Discrete Event Simulation Time Unit in JavaJava中的离散事件模拟时间单位
【发布时间】:2017-05-31 09:37:02
【问题描述】:

我正在Java中进行离散事件模拟,时间相关的代码如下;

class Event implements Runnable, Comparable {
    double time;
    Runnable runnable;

    Event(double time, Runnable aRunnable) {
        this.time = time;
        runnable = aRunnable;
    }

    public boolean lessThan(Comparable y) {
        Event e = (Event) y; // Will throw an exception if y is not an Event
        return this.time <= e.time;
    }

    @Override
    public void run() {
        runnable.run();

    }
}

class Simulator extends AbstractSimulator {

    static Random rnd;
    static double time;
    double endTime;


    static double now() {
        return time;
    }

    Simulator(long seed, double simDuration) {
        time = 0.0;
        events = new ListQueue();
        rnd = new Random(seed);
        endTime = simDuration;
    }

    void doAllEvents() {
        Event e;
        while ((e = (Event) events.removeFirst()) != null && time < endTime) {
            if(time > e.time)
                System.out.printf("Something is worng! time=%f eventtime=%f",time,e.time);
            time = e.time;
            e.run();
            System.out.printf("\n Time = %f", time);

        }
    }

我根据事件失败时间考虑结果,但我需要在绘制它时使用一个单位。

Java 使用哪个单位进行模拟时间?还是我可以将它们视为第二个?或者是否有任何计算可以将其转换为现实世界时间?

提前致谢,

最好的问候,

更新:

感谢您的回答,我试图测量确切的时间,但我在这里遇到了问题。现有的虚拟仿真时间正在测量网络寿命。并且它与示例的确切时间不同;当我为 75 台设备运行模拟时,netorklifetime 更短,比如说 70.0,但实际时间超过 35 台设备,寿命为 1500.0。发生这种情况是因为每个设备的事件都在重复。

我需要在这里找到虚拟模拟时间的单位。

再次感谢...

【问题讨论】:

  • 注意:实现Comparable&lt;Event&gt;,而不是原始Comparable
  • 我会使用 System.nanoTime() (long) 和 TimeUnit 类来展示它们。 nanoTime() 只是用来测量经过的时间

标签: java clock seed


【解决方案1】:

您可以使用ScheduledExecutorService 来模拟离散事件,例如

List<Event> events = new ArrayList<Event>();
ScheduledExecutorService executor =  Executors.newScheduledThreadPool(4);
for (Event event : events) {
    executor.schedule(event, (long) event.time, TimeUnit.MILLISECONDS);
}
try {
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
    e.printStackTrace();
}

几点,可能会有所帮助:

  1. 我认为将池的大小设置为超过您拥有的核心数量(在上面的示例中为 4 个)是不值得的
  2. 上面的sn-p不需要Event实现Comparable
  3. 我会使用long 类型作为时间字段而不是double

更新 如果您不想使用执行器或线程,您可以按时间对事件进行排序,然后使用while 循环等待事件触发,如下所示:

List<Event> events = new ArrayList<Event>();
events.add(new Event(1000d, () -> System.out.println("event1")));
events.add(new Event(2000d, () -> System.out.println("event2")));
//adding more events ...
Collections.sort(events);

//Fix start time
long start = System.currentTimeMillis();
for (Event event : events) {

    //Wait until event time is <= than current - start time
    while (event.time > System.currentTimeMillis() - start);
    event.run();
}

【讨论】:

    猜你喜欢
    • 2012-10-22
    • 1970-01-01
    • 2019-09-07
    • 2011-04-29
    • 2011-06-25
    • 1970-01-01
    • 2014-04-12
    • 1970-01-01
    • 2017-12-30
    相关资源
    最近更新 更多