-
Notifications
You must be signed in to change notification settings - Fork 14
/
AsyncThread.java
60 lines (57 loc) · 1.58 KB
/
AsyncThread.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
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
class Requestor {
public String execute(String req) {
return "response:" + req;
}
public String error(String req) {
return "response:" + req + ":" + "TIMEDOUT";
}
// @include
public String execute(String req, long delay) {
try {
// simulate the time taken to perform a computation
Thread.sleep(delay);
} catch (InterruptedException e) {
return error(req);
}
return execute(req);
}
// @exclude
public void ProcessResponse(String response) {
System.out.println("ProcessResponse:" + response);
return;
}
}
public class AsyncThread {
public static final long TIMEOUT = 500L;
public static void main(String [] args) {
Dispatch(new Requestor(), "t1", 1000L);
Dispatch(new Requestor(), "t2", 100L);
Dispatch(new Requestor(), "t3", 10L);
Dispatch(new Requestor(), "t4", 1L);
Dispatch(new Requestor(), "t5", 200L);
}
// @include
public static void Dispatch(final Requestor r, final String request,
final long delay) {
Runnable task = new Runnable() {
public void run() {
Runnable actualTask = new Runnable() {
public void run() {
String response = r.execute(request, delay);
r.ProcessResponse(response);
}
};
Thread innerThread = new Thread(actualTask);
innerThread.start();
try {
Thread.sleep(TIMEOUT);
innerThread.interrupt();
} catch(InterruptedException e) {
e.printStackTrace();
}
}
};
new Thread(task).start();
}
// @exclude
}