Java 方法执行超时时间

执行时间超时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  
import java.util.concurrent.*;

public class MethodTimeOutTest {

public static void main(String[] args) throws ExecutionException, InterruptedException {

ExecutorService executorService = Executors.newSingleThreadExecutor();

Future<String> future = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
System.out.println("开始执行");
TimeUnit.SECONDS.sleep(2);
return "执行完成";
}
});

try {
String result = future.get(1, TimeUnit.SECONDS); // 阻塞直到执行完成,设置超时间
System.out.println(result);
} catch (TimeoutException e) {
System.out.println("超时了");
} finally {
executorService.shutdown();
System.out.println("over !!!!! ");
}

}
}

输出

开始执行
超时了
over !!!!! 
在超时时间内完成执行

超时时间设置为3秒

1
2
3
……
String result = future.get(3, TimeUnit.SECONDS); // 阻塞直到执行完成,设置超时间
……

输出

开始执行
执行完成
over !!!!!