java异步回调demo


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.*;

interface ICallback {
void getResult(int s);
}

class Calc {
public void calc(int i, ICallback callback) throws Exception {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int s = i * i;
Thread.sleep(5000);
System.out.println("do in future task. " + Thread.currentThread().getName());
callback.getResult(s);
return s;
}
});
new Thread(futureTask).start();
}
}

public class App {
public static void main(String[] args) throws Exception {
ICallback callback = new ICallback() {
@Override
public void getResult(int s) {
System.out.println(s);
}
};
new Calc().calc(1000, callback);
System.out.println("do in main");
}
}