How to timeout a thread

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

    Here is my really simple to use helper class to run or call piece of Java code :-)

    This is based on the excellent answer from BalusC

    package com.mycompany.util.concurrent;
    
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    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;
    
    /**
     * Calling {@link Callable#call()} or Running {@link Runnable#run()} code
     * with a timeout based on {@link Future#get(long, TimeUnit))}
     * @author pascaldalfarra
     *
     */
    public class CallableHelper
    {
    
        private CallableHelper()
        {
        }
    
        public static final void run(final Runnable runnable, int timeoutInSeconds)
        {
            run(runnable, null, timeoutInSeconds);
        }
    
        public static final void run(final Runnable runnable, Runnable timeoutCallback, int timeoutInSeconds)
        {
            call(new Callable()
            {
                @Override
                public Void call() throws Exception
                {
                    runnable.run();
                    return null;
                }
            }, timeoutCallback, timeoutInSeconds); 
        }
    
        public static final  T call(final Callable callable, int timeoutInSeconds)
        {
            return call(callable, null, timeoutInSeconds); 
        }
    
        public static final  T call(final Callable callable, Runnable timeoutCallback, int timeoutInSeconds)
        {
            ExecutorService executor = Executors.newSingleThreadExecutor();
            try
            {
                Future future = executor.submit(callable);
                T result = future.get(timeoutInSeconds, TimeUnit.SECONDS);
                System.out.println("CallableHelper - Finished!");
                return result;
            }
            catch (TimeoutException e)
            {
                System.out.println("CallableHelper - TimeoutException!");
                if(timeoutCallback != null)
                {
                    timeoutCallback.run();
                }
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            catch (ExecutionException e)
            {
                e.printStackTrace();
            }
            finally
            {
                executor.shutdownNow();
                executor = null;
            }
    
            return null;
        }
    
    }
    

提交回复
热议问题