Java:执行Runnable固定次数

时间:2015-04-18 16:43:27

标签: java threadpool scheduledexecutorservice

所以我有一段代码要反复执行。我得到这个部分。问题是我想以固定的间隔执行代码,但只有固定的数量(在这种情况下为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);
    }
}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

试试这个

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

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