设置方法线程的最大执行时间

设置方法线程的最大执行时间,第1张

设置方法/线程的最大执行时间

您可以通过将工作发送给执行者来做到这一点

 public static void main(String[] args) {    ExecutorService executor = Executors.newFixedThreadPool(4);    Future<?> future = executor.submit(new Runnable() {        @Override        public void run() { writeToDb(); //        <-- your job        }    });    executor.shutdown(); //        <-- reject all further submissions    try {        future.get(8, TimeUnit.SECONDS);  //     <-- wait 8 seconds to finish    } catch (InterruptedException e) {    //     <-- possible error cases        System.out.println("job was interrupted");    } catch (ExecutionException e) {        System.out.println("caught exception: " + e.getCause());    } catch (TimeoutException e) {        future.cancel(true);   //     <-- interrupt the job        System.out.println("timeout");    }    // wait all unfinished tasks for 2 sec    if(!executor.awaitTermination(2, TimeUnit.SECONDS)){        // force them to quit by interrupting        executor.shutdownNow();    }}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5013664.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-15
下一篇 2022-11-14

发表评论

登录后才能评论

评论列表(0条)

保存