0%

Java中对方法的执行设置超时

利用FutureTask对一个方法设置执行超时的操作

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
35
36
37
38
39
40
41
42
43
44
45
package io.github.jiezhi.concurrent;

import java.util.concurrent.*;

/**
* Created by jiezhi on 12/3/15.
*/
public class TimeoutDemo {
private static final String TAG = "jiezhi:TimeoutDemo";

public static void main(String args[]){
runFunTimeout();
}

/**
* 在固定时间内执行一个函数,超时则退出
*/
private static void runFunTimeout() {
FutureTask<Object> task = new FutureTask<>(() -> needTime(10 * 1000));

ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(task);

try {
task.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}

executor.shutdown();
}

private static int needTime(long t) {
try {
Thread.sleep(t);
} catch (InterruptedException e) {
e.printStackTrace();
}
return 1;
}


}


Welcome to my other publishing channels