forked from wxdong5211/JavaUtils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFuncCourser.java
More file actions
58 lines (48 loc) · 1.42 KB
/
FuncCourser.java
File metadata and controls
58 lines (48 loc) · 1.42 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
package com.impler.utils;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
/**
* 猎犬模式
* @author Invalid
*/
public class FuncCourser {
private FuncCourser(){}
private static ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private int count;
@Override
public Thread newThread(Runnable task) {
count++;
Thread invoke = new Thread(task);
invoke.setName("InvokeThread-"+count);
invoke.setDaemon(true);
return invoke;
}
});
public static <T> T call(Callable<T> task, TimeUnit unit, long timeout) throws TimeoutException{
Future<T> handler = executor.submit(task);
T result;
try {
result = handler.get(timeout, unit);
} catch (Exception e) {
if(e instanceof TimeoutException)
throw new TimeoutException("invoke timeout");
throw new RuntimeException(e);
}
return result;
}
public static void call(Runnable task, TimeUnit unit, long timeout) throws TimeoutException{
Future<?> handler = executor.submit(task);
try {
handler.get(timeout, unit);
} catch (Exception e) {
if(e instanceof TimeoutException)
throw new TimeoutException("invoke timeout");
throw new RuntimeException(e);
}
}
}