GeXiangDong

精通Java、SQL、Spring的拼写,擅长Linux、Windows的开关机

0%

Java 给一个任务设置超时返回

可以通过CompletableFuture 来执行某个任务,超时后放弃任务。

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
31
32
33
34
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CompletableFutureTester {

public static void main(String[] argvs) {
CompletableFuture<String> cf1 = CompletableFuture.supplyAsync(() -> {
System.out.println("enter cf");
try {
//sleep 3秒
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("s1");
return "done";
});

try {
//试图在2秒内得到结果,否则算超时
String result = cf1.get(2, TimeUnit.SECONDS);
System.out.println("result is : " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
System.out.println("超时未得到结果");
e.printStackTrace();
}
}
}