Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

java - 如何延迟Java?(How do I make a delay in Java?)

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

(我正在尝试用Java做某事,而我需要一些在while循环中等待/延迟几秒钟的时间。)

while (true) {
    if (i == 3) {
        i = 0;
    }

    ceva[i].setSelected(true);

    // I need to wait here

    ceva[i].setSelected(false);

    // I need to wait here

    i++;
}

I want to build a step sequencer and I'm new to Java.

(我想构建一个步进音序器,并且对Java还是陌生的。)

Any suggestions?

(有什么建议么?)

  ask by ardb translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to pause then use java.util.concurrent.TimeUnit :

(如果要暂停,请使用java.util.concurrent.TimeUnit :)

TimeUnit.SECONDS.sleep(1);

To sleep for one second or

(睡一秒钟或)

TimeUnit.MINUTES.sleep(1);

To sleep for a minute.

(睡一分钟。)

As this is a loop, this presents an inherent problem - drift.

(由于这是一个循环,因此存在一个固有的问题-漂移。)

Every time you run code and then sleep you will be drifting a little bit from running, say, every second.

(每次您运行代码然后进入睡眠状态时,您的运行都会有点漂移,例如每秒。)

If this is an issue then don't use sleep .

(如果这是一个问题,那就不要sleep 。)

Further, sleep isn't very flexible when it comes to control.

(此外,就控制而言, sleep不是很灵活。)

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay .

(为了每秒运行一次任务或延迟一秒钟,我强烈建议您使用ScheduledExecutorService以及scheduleAtFixedRatescheduleWithFixedDelay 。)

For example, to run the method myTask every second (Java 8):

(例如,要myTask运行方法myTask (Java 8):)

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

And in Java 7:

(在Java 7中:)

public static void main(String[] args) {
    final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    executorService.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            myTask();
        }
    }, 0, 1, TimeUnit.SECONDS);
}

private static void myTask() {
    System.out.println("Running");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...