java中的简单超时

Yuv*_*raj 34 java timeout timeoutexception

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

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

Tre*_*ein 37

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

选项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();
Run Code Online (Sandbox Code Playgroud)

选项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();
Run Code Online (Sandbox Code Playgroud)

这些只是一个草案,所以你可以得到主要的想法.

  • 这可以更好地回答http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread (3认同)
  • 我认为[this](http://stackoverflow.com/questions/2275443/how-to-timeout-a-thread/2275596#2275596)仍然是更好的答案 (2认同)