Java loop for a certain duration

后端 未结 8 2139
花落未央
花落未央 2020-12-13 22:10

Is there a way I can do a for loop for a certain amount of time easily? (without measuring the time ourselves using System.currentTimeMillis() ?)

I.e. I want to do s

8条回答
  •  死守一世寂寞
    2020-12-13 22:38

    I think that this is what you want:

    private final Thread thisThread = Thread.current();
    private final int timeToRun = 120000; // 2 minutes;
    
    new Thread(new Runnable() {
        public void run() {
            sleep(timeToRun);
            thisThread.interrupt();
        }
    }).start();
    
    while (!Thread.interrupted()) {
        // do something interesting.
    }
    

    This avoids doing repeated syscalls to get the system clock value (which can be rather expensive) and polls the current thread's interrupted flag instead (much cheaper).

    EDIT

    There is actually no safe alternative to polling the clock or polling a flag. In theory, you could modify the above fragment to call the deprecated Thread.stop() method instead of Thread.interrupt().

    (I do NOT recommend using Thread.stop() and friends. They are flawed, and dangerous to use. I'm just posing this as a theoretical alternative.)

    EDIT 2

    Just to point out that using Thread.interrupt() has the advantages over setting a shared flag:

    • Thread.interrupt() will cause certain blocking I/O and synchronization methods to unblock and throw a checked exception. Updating a shared flag won't do this.

    • Some third-party libraries also check the interrupt flag to see if they should stop what they are currently doing.

    • If your loop involves calls to other methods, etc, Thread.interrupt() means that you don't need to worry about those methods can access the flag ... if they need to.

    EDIT 3

    Just to add that sleep(N) is not guaranteed to wake the sleeping thread up after exactly N milliseconds. But under normal circumstances, it will be reasonably close.

提交回复
热议问题