java - 如何在android studio中运行特定时间的线程
问题描述
我正在使用一个线程来运行我的数据库连接检查我希望这个线程运行特定的时间,我尝试使用倒数计时器类,但是没有,请提供任何帮助。
解决方案
您可以使用ExecutorService并执行以下操作:
public class ExampleClass {
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new DatabaseConnection());
try {
future.get(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
...
} catch (ExecutionException e) {
...
} catch (TimeoutException e) {
// do something in case of timeout
future.cancel(true);
}
executor.shutdownNow();
}
}
class DatabaseConnection implements Callable<String> {
@Override
public String call() throws Exception {
while (!Thread.interrupted()) {
// Perform your task here, e.g. connect to your database
}
return "Success";
}
}
通过这种方式,您可以在另一个线程上执行任务,并具有您想要的任何超时。在上面的代码片段中,设置了三秒的超时。
推荐阅读
- apache-tika - TIKA - 计算文档的内容编码
- java - 定位器有 4 个匹配节点,当我们有 4 个元素匹配时,如何在 Selenium 中编写 xpath?
- amazon-web-services - 如何立即使用 EIP 启动实例?
- python - NameError 无法使用导入的变量 [已解决]
- php - 无法设置 Telegram 表单的样式和格式
- firebase - Firebase 存储是否支持负载平衡(/GoogleCDN/CloudArmor)?因为安全规则
- reactjs - 当我尝试运行“yarn build”时出现此错误
- twig - Symfony 4.4.2 切换语言环境 - TWIG 中的语言环境丢失
- visual-studio-code - 与 Visual Studio Code(实时服务器安装)相关的问题
- python - 如何在 control.root_locus 中获得欧米茄阻尼图?