谁能指导我如何在java中使用简单的超时?基本上在我的项目中我正在执行一条语句br.readLine()
,它正在读取调制解调器的响应。但有时调制解调器没有响应。为此,我想添加一个超时。
我正在寻找类似的代码:
try {
String s= br.readLine();
} catch(TimeoutException e) {
System.out.println("Time out has occurred");
}
您要找的东西都可以找到here https://stackoverflow.com/questions/2758612/executorservice-that-interrupts-tasks-after-a-timeout。可能存在一种更优雅的方式来实现这一点,但一种可能的方法是
选项 1(首选):
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:
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();
这些只是草稿,以便您可以了解主要想法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)