How to timeout a thread

后端 未结 17 1139
时光说笑
时光说笑 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:28

    Indeed rather use ExecutorService instead of Timer, here's an SSCCE:

    package com.stackoverflow.q2275443;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.Future;
    import java.util.concurrent.TimeUnit;
    import java.util.concurrent.TimeoutException;
    
    public class Test {
        public static void main(String[] args) throws Exception {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future future = executor.submit(new Task());
    
            try {
                System.out.println("Started..");
                System.out.println(future.get(3, TimeUnit.SECONDS));
                System.out.println("Finished!");
            } catch (TimeoutException e) {
                future.cancel(true);
                System.out.println("Terminated!");
            }
    
            executor.shutdownNow();
        }
    }
    
    class Task implements Callable {
        @Override
        public String call() throws Exception {
            Thread.sleep(4000); // Just to demo a long running task of 4 seconds.
            return "Ready!";
        }
    }
    

    Play a bit with the timeout argument in Future#get() method, e.g. increase it to 5 and you'll see that the thread finishes. You can intercept the timeout in the catch (TimeoutException e) block.

    Update: to clarify a conceptual misunderstanding, the sleep() is not required. It is just used for SSCCE/demonstration purposes. Just do your long running task right there in place of sleep(). Inside your long running task, you should be checking if the thread is not interrupted as follows:

    while (!Thread.interrupted()) {
        // Do your long running task here.
    }
    

提交回复
热议问题