TaskTimeout.java
1.98 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.gimi.common.cinema.utils;
import android.text.TextUtils;
import java.io.File;
import java.util.concurrent.*;
/**
* 启动一个任务,然后等待任务的计算结果,如果等待时间超出预设定的超时时间,则中止任务。
*
* @author Chen Feng
*/
public class TaskTimeout {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
execTask(exec, 15, ""); // 任务成功结束后等待计算结果,不需要等到15秒
execTask(exec, 5, ""); // 只等待5秒,任务还没结束,所以将任务中止
exec.shutdown();
}
public static boolean execTask(ExecutorService exec, int timeout, String path) {
ChargeTask task = new ChargeTask(path);
Future<Boolean> future = exec.submit(task);
Boolean taskResult = null;
// String failReason = null;
try {
// 等待计算结果,最长等待timeout hao秒,timeout秒后中止任务
taskResult = future.get(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
// failReason = "主线程在等待计算结果时被中断";
} catch (TimeoutException e) {
e.printStackTrace();
// failReason = "主线程等待计算结果超时,因此中断任务线程!";
exec.shutdownNow();
}
if (taskResult == null) {
return false;
}
return taskResult;
}
public static boolean execTask(){
return false;
}
//do what you want to do
class PingTask implements Callable<Boolean> {
String path;
public PingTask(String path) {
this.path = path;
}
@Override
public Boolean call() throws Exception {
if (TextUtils.isEmpty(path)) {
return false;
}
return new File(path).exists();
}
}
}