java中的简单超时 [英] Simple timeout in java

查看:154
本文介绍了java中的简单超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以指导我如何在java中使用简单的超时吗?基本上在我的项目中,我正在执行一个语句 br.readLine(),它正在读取调制解调器的响应。但有时调制解调器没有响应。为此我想添加一个超时。
我正在寻找类似的代码:

Can anyone guide me on how I can use a simple timeout in java? Basically in my project I'm executing a statement br.readLine(), which is reading a response from a modem. But sometimes the modem isn't responding. For that purpose I want to add a timeout. I'm looking for a code like:

try {
    String s= br.readLine();
} catch(TimeoutException e) {
    System.out.println("Time out has occurred");
}


推荐答案

你在找什么可以找到这里。可能存在一种更优雅的方式来实现这一点,但一种可能的方法是

What you are looking for can be found here. It may exist a more elegant way to accomplish that, but one possible approach is

final Duration timeout = Duration.ofSeconds(30);
ExecutorService executor = Executors.newSingleThreadExecutor();

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

try {
    handler.get(timeout.toMillis(), TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
    handler.cancel(true);
}

executor.shutdownNow();



选项2:



Option 2:

final Duration timeout = Duration.ofSeconds(30);
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);

final Future<String> handler = executor.submit(new Callable() {
    @Override
    public String call() throws Exception {
        return requestDataFromModem();
    }
});

executor.schedule(new Runnable() {
    @Override
    public void run(){
        handler.cancel(true);
    }      
}, timeout.toMillis(), TimeUnit.MILLISECONDS);

executor.shutdownNow();

这些只是草稿,以便您可以获得主要想法。

Those are only a draft so that you can get the main idea.

这篇关于java中的简单超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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