目前我正在尝试下面的代码。问题是在超时(5秒)catch(TimeoutException e)块正在执行但无法取消执行查询。我希望在超时后取消执行并继续下一部分代码。
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable() {
public String call() throws Exception {
System.out.println("task running!");
ResultSet rs = psLoadingStr.executeQuery();
return "OK";
}
});
try
{
future.get(5, TimeUnit.SECONDS); //timeout is in 5 seconds
}
catch (TimeoutException e)
{
System.err.println("Timeout");
future.cancel(true);
}
executor.shutdownNow();
答案 0 :(得分:0)
您可以在执行查询时设置超时。如果查询没有及时完成并超时,则抛出SQLException:
preparedstatement.setQueryTimeout(seconds);
ResultSet resultSet = preparedStatement.executeQuery();
while( resultSet.next() ){
// do some stuff
}
看看setQueryTimeout documentation