How to timeout a thread

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

    Great answer by BalusC's:

    but Just to add that the timeout itself does not interrupt the thread itself. even if you are checking with while(!Thread.interrupted()) in your task. if you want to make sure thread is stopped you should also make sure future.cancel() is invoked when timeout exception is catch.

    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) {
                //Without the below cancel the thread will continue to live 
                // even though the timeout exception thrown.
                future.cancel();
                System.out.println("Terminated!");
            } 
    
            executor.shutdownNow();
        } 
    } 
    
    class Task implements Callable {
        @Override 
        public String call() throws Exception {
          while(!Thread.currentThread.isInterrupted()){
              System.out.println("Im still running baby!!");
          }          
        } 
    } 
    

提交回复
热议问题