每隔n秒增加一个变量java

时间:2018-04-08 15:47:58

标签: java

我这里有一种方法可以模拟烤面包。

private int temp = 0;
private int maxTemp = 5;

public void Toasting(){
        if(breadLevel >= 0){
            toasting = true;
            temp += 1;

        } else {
            toasting = false;
        }
        System.out.println(breadLevel);
    }

基本上如果烤面包机里有面包,那就是烤面包。我想每隔几秒增加一次临时变量,当它达到最大温度时。敬酒=假。

我将如何得到这个。

2 个答案:

答案 0 :(得分:0)

一个好主意是使用ScheduledExecutorService为您处理线程:

public class Main {

    static ScheduledFuture<?> future;

    public class IncrementTask implements Runnable {

        private int value = 0;
        private final int max;
        private boolean toasting = true;

        public IncrementTask(int max) {
            this.max = max;
        }

        @Override
        public void run() {
            if (value < max) {
                value++;
                System.out.println("Toasing...value is " + value);
            }
            else {
                toasting = false;
                System.out.println("Done toasting");
                future.cancel(true);
            }
        }

        public boolean isToasting() {
            return toasting;
        }
    }

    public static void main(String[] args) {

        Runnable incrementTask = new IncrementTask(10);
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
        future = executor.scheduleAtFixedRate(incrementTask, 0, 1, TimeUnit.SECONDS);
    }
}

请注意,此代码每1秒运行一次,并在toasting设置为false后停止运行。以下调用中的值0表示初始延迟(开始Runnable之前多久,1表示期间,TimeUnit.SECONDS表示时间刻度:

scheduleAtFixedRate(incrementTask, 0, 1, TimeUnit.SECONDS);

要获取toasting的值,请致电incrementTask.getToasting()。有关在toasting为真后如何停止递增操作的详细信息,请参阅How to stop a task in ScheduledThreadPoolExecutor once I think it's completed

答案 1 :(得分:0)

这样可行:

while (true) {
    value++;
    try {
        Thread.sleep(5000); // sleep for 5000 milliseconds
    } catch (InterruptedException e) {}
}