Java:执行Runnable固定次数

Java: execute Runnable fixed number of times

所以我有一段代码要反复执行。我明白这部分了。问题是我想以固定的时间间隔执行代码,但只执行固定次数(在本例中为 1440 次)。

知道我该怎么做吗?

代码如下:

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;


public class Simulator {

    public static int TICK = 10;
    public static int NUM_OF_SERVERS = 3;
    public static int LENGTH_OF_SIMULATION = 1440;

    public static void main(String[] args) {


        final MultiQueueControlSystem multiController = MultiQueueControlSystem.getInstance();
        final SingleQueueControlSystem singleController = SingleQueueControlSystem.getInstance();

        multiController.generateQueuesAndServers(NUM_OF_SERVERS);
        singleController.generateQueuesAndServers(NUM_OF_SERVERS);

        final ScheduledExecutorService ticker = Executors.newSingleThreadScheduledExecutor();

        ticker.scheduleAtFixedRate(new Runnable() {

            int currentTime = 0;

            public void run() {

                if(currentTime < LENGTH_OF_SIMULATION) {
                    currentTime = currentTime + 1;
                } else {
                    ticker.shutdown();
                    return;
                }

                multiController.customerArrival();
                multiController.allocateCustomersToServers();
                multiController.removeFinishedCustomersFromServers();

                singleController.customerArrival();
                singleController.allocateCustomersToServers();
                singleController.removeFinishedCustomersFromServers();
            }
        }, 1, TICK, TimeUnit.MILLISECONDS);
    }
}

考虑为您的可运行对象提供对 ScheduledExecutorService 的引用。然后不是以固定速率调度,而是为将来的执行调度。让可运行实例保持跟踪器(通过 AtomicInteger)它已执行了多少次。当它完成它的正常执行时,它可以安排自己以供将来执行。一旦它执行了所需的次数,它就不会再次安排自己。

试试这个

取任何整数变量runCount(每次循环后递增)和servicescheduleAtFixedRate方法返回的对象

if(runCount == LENGTH_OF_SIMULATION ) { service.cancel(false); }