是否可以在 Java 中的指定时间内停止函数的执行? [英] Is it possible to stop a function's execution within a specified time in Java?

查看:39
本文介绍了是否可以在 Java 中的指定时间内停止函数的执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在java中如何在指定时间内停止指定函数的执行

I want to know how to stop a specified function's execution within a specified time in java.

例如:我可能会调用一个名为 print_data() 的函数.如果执行需要更多时间,我将不得不停止该函数的执行.

For example: I may call a function called print_data(). If it takes more time to execute, I will have to stop that function's execution.

有没有可能像这样停止执行?

Is it possible to stop the execution like this?

提前致谢

推荐答案

您可以对函数添加一些检查:保存函数开始工作时的时间戳,然后定期检查函数内部的时间戳,如果函数运行时间过长则抛出异常.

You could add some checks to your function: save the timestamp when function started working and then periodically checking that inside the function, throwing an exception if function takes too long.

这是在 Java 中完成此类任务的最简洁的方法.

This is the cleanest way to accomplish such task in Java.

这篇关于是否可以在 Java 中的指定时间内停止函数的执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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