-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSynchronousExecutor.java
More file actions
57 lines (48 loc) · 1.47 KB
/
SynchronousExecutor.java
File metadata and controls
57 lines (48 loc) · 1.47 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
package interview;
interface Callback {
public void done();
}
class Executor {
public void asynchronousExecution(Callback callback) throws Exception {
Thread t = new Thread(() -> {
// Do some useful work
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
callback.done();
});
t.start();
}
}
public class SynchronousExecutor extends Executor {
@Override
public void asynchronousExecution(Callback callback) throws Exception {
Object signal = new Object();
final boolean[] isDone = new boolean[1];
Callback cb = new Callback() {
@Override
public void done() {
callback.done();
synchronized (signal) {
signal.notify();
isDone[0] = true;
}
}
};
// Call the asynchronous executor
super.asynchronousExecution(cb);
synchronized (signal) {
while (!isDone[0]) {
signal.wait();
}
}
}
public static void main( String args[] ) throws Exception {
SynchronousExecutor executor = new SynchronousExecutor();
executor.asynchronousExecution(() -> {
System.out.println("I am done");
});
System.out.println("main thread exiting...");
}
}