设置方法/线程的最大执行时间 [英] Setting a maximum execution time for a method/thread

查看:281
本文介绍了设置方法/线程的最大执行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方法,写入数据库。要求是确保此方法在一定时间过后不会执行。

I have a method, which writes to the database. The requirement is to make sure that this method does not execute after a certain time elapses. If it returns before that, then nothing should be done.

我可以想到的一个基本方法是做这样的事情。

The one basic approach that I can think of is doing something like this.

public class LimitedRuntime {

    public static void writeToDb(){
            // writes to the database
    }

    public static void main(String[] args) {
        long totalExecutionTime = 8000L;
        long startTime = System.currentTimeMillis();

        while(System.currentTimeMillis() - startTime < totalExecutionTime )
        {
            writeToDb();
        }   
    }
}

即使该方法在最大总执行时间之前返回,即使程序停止,以便等待时间过去。

One problem with this approach is that even if the method returns before the max total execution time, even then the program halts so as to wait for the time to elapse.

我如何做到这一点更好或者可能更正确)?如果我们使用 Thread ,我们如何找出哪个 Thread 执行该方法?

How can I do this better (or maybe more correctly) ? And if we use Thread, how can we find out which Thread executes that method ?

推荐答案

您可以将您的工作发送给执行者:

You can do this by sending your job to an executor:

 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();
    }
}

这篇关于设置方法/线程的最大执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆