How to timeout a thread

后端 未结 17 1368
时光说笑
时光说笑 2020-11-22 01:01

I want to run a thread for some fixed amount of time. If it is not completed within that time, I want to either kill it, throw some exception, or handle it in some way. How

17条回答
  •  醉梦人生
    2020-11-22 01:49

    I think the answer mainly depends on the task itself.

    • Is it doing one task over and over again?
    • Is it necessary that the timeout interrupts a currently running task immediately after it expires?

    If the first answer is yes and the second is no, you could keep it as simple as this:

    public class Main {
    
        private static final class TimeoutTask extends Thread {
            private final long _timeoutMs;
            private Runnable _runnable;
    
            private TimeoutTask(long timeoutMs, Runnable runnable) {
                _timeoutMs = timeoutMs;
                _runnable = runnable;
            }
    
            @Override
            public void run() {
                long start = System.currentTimeMillis();
                while (System.currentTimeMillis() < (start + _timeoutMs)) {
                    _runnable.run();
                }
                System.out.println("execution took " + (System.currentTimeMillis() - start) +" ms");
            }
    
        }
    
        public static void main(String[] args) throws Exception {
            new TimeoutTask(2000L, new Runnable() {
    
                @Override
                public void run() {
                    System.out.println("doing something ...");
                    try {
                        // pretend it's taking somewhat longer than it really does
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }).start();
        }
    }
    

    If this isn't an option, please narrow your requirements - or show some code.

提交回复
热议问题