每隔x分钟执行一段代码

时间:2013-04-16 01:59:37

标签: java

我需要每2分钟为队列添加一个“car”,并每2分钟从队列中删除一个“car”。然后在可能的情况下,当队列以相同的时间增量打开时,将汽车从堆栈移动到队列中。

public static void main(String[] args) {

    int lp = 10000;  
    int i = 10;       
    int maxQueue = 0;
    int maxStack = 0;
    Lstack stack = new Lstack();
    Lqueue queue = new Lqueue();
    int cr = 1; //cars removed

    Scanner input = new Scanner(System.in);

    for (int size = 0; size < 26; size++) {


        **// arrivals, need to add 2 min wait**           
        if (maxQueue < 6 ){                        
        Car car = new Car(Integer.toString(lp), 'X');            
        queue.insert(car);
        lp = lp + i;
        maxQueue++;
    }     

    else if (maxQueue > 6){ 
       Car car = new Car(Integer.toString(lp), 'X');
       stack.push(car);
       lp = lp + i;
       maxStack++;
    }

    else if((maxQueue > 6) && (maxStack > 6)){
       System.out.println("Sorry there isn't enough room");
       cr++;
       System.out.println("New amount to be taken away:" + cr);
    }    

      **// removals, need to add the wait 5 min**
        if (maxQueue != 0){            
        for(i = 0; i < cr; i++){
            queue.remove();
            System.out.println("Car" + lp + "was/were removed");
        }            
        maxQueue--;
        }

        else if( maxQueue == 0){
            cr++;
        }
        System.out.println("Before Driveway Moves:");
        queue.display();
        stack.display();

        // empty driveway

        while((maxQueue < 6) && (maxStack != 0)){
           System.out.println("Moving car " + lp + " to the driveway");
            queue.insert(stack.pop());
        }
        System.out.println("After Driveway Moves: ");
        queue.display();
        stack.display();

    }
}

2 个答案:

答案 0 :(得分:1)

总是可以使用计时器。您希望删除或插入是否相互独立?

这是计时器最简单的例子:

import java.util.Timer;
import java.util.TimerTask;

public class TimerEx extends TimerTask {

    @Override
    public void run() {
        System.out.println("I get printed every 2 minutes.");
    }

    public static void main(String[] args) {
        Timer t = new Timer();
        t.scheduleAtFixedRate(new TimerEx(), 0, 2*60*1000);
    }
}

答案 1 :(得分:0)

根据我的理解,你不想只是等待,而是每隔一段时间添加/删除汽车(在2,4,6 ......分钟后添加汽车,在5,10之后删除......而不是全部添加间隔2分钟的汽车,然后每隔5分钟取出所有车辆。

最干净的方法是使用一个会为你计算间隔的线程。你可以试试这门课。

public class Timer implements Runnable
{
    private TimerCallback pCallback;
    private Thread pThread;
    private long pInterval;
    private int pTimerId;

    private boolean pStopRequested;

    public interface TimerCallback
    {
        public void onTimerTick(int timerId);
    }

    public Timer(int id, long interval, TimerCallback callback)
    {
        pStopRequested = false;
        pTimerId = id;
        pInterval = interval;
        pCallback = callback;
        pThread = new Thread(this);
        pThread.start();
    }

    public void stopTimer()
    {
        pStopRequested = true;
        pThread.interrupt();
    }

    @Override
    public void run() 
    {   
        while(true)
        {
            // wait
            try
            {
                Thread.sleep(pInterval);
            }
            catch(InterruptedException e)
            {
                // Restore the interrupted status
                Thread.currentThread().interrupt();
            }

            if(pStopRequested)
                return;
            else
                pCallback.onTimerTick(pTimerId);
        }   
    }
}

这是如何使用它的一个例子。

public class MyCarsQueue
{
    private static final int MINUTE = 1*1000;// 60*1000;
    private static final int LIMIT = 26;

    public synchronized void addCar()
    {
        // do what you want to do when a new car is added
    }

    public synchronized void removeCar()
    {
        // do what you want to do when a car is removed

    }

    public static void main(String args)
    {
        final MyCarsQueue driveway = new MyCarsQueue();
        final int[] limit = new int[1];

        // create a callback for timers
        Timer.TimerCallback callback = new Timer.TimerCallback() {
            @Override
            public void onTimerTick(int timerId) 
            {
                if(timerId == 0) driveway.addCar();
                if(timerId == 1) driveway.removeCar();

                synchronized (limit) {
                    limit[0]++;
                    limit.notify();                 
                }
            }
        };

        // start timers
        Timer twoMinutesTimer = new Timer(0, 2*MINUTE, callback);
        Timer fiveMinutesTimer = new Timer(1, 5*MINUTE, callback);

        // wait until timers have completed
        try
        {
            synchronized (limit) {
                while(limit[0] < LIMIT)
                {
                    limit.wait();
                }
            }
        }
        catch (InterruptedException e) {
            // Restore the interrupted status
            Thread.currentThread().interrupt();
        }

        // finished (the limit has been reached)
        fiveMinutesTimer.stopTimer();
        twoMinutesTimer.stopTimer();
    }
}

您可以使用现有的ScheduledExecutorService

代替Timer
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

Runnable run = new Runnable() { public void run() { driveway.addCar(); }};
ScheduledFuture<?> delayHandle 
    = scheduler.scheduleAtFixedRate(run, 2, 26*2, TimeUnit.MINUTES);

// wait until delayHandle.isDone(); returns false