Skip to content

Commit edf0a09

Browse files
committed
notify example
1 parent dcc0380 commit edf0a09

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed
Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
package benblack86.notification;
2+
3+
import java.util.Random;
4+
import java.util.concurrent.ExecutorService;
5+
import java.util.concurrent.Executors;
6+
7+
public class Notify {
8+
private static ExecutorService service = Executors.newFixedThreadPool(2);
9+
10+
public static void main(String args[]) {
11+
final Notify notify = new Notify();
12+
long start = System.currentTimeMillis();
13+
14+
service.submit(new Runnable() {
15+
16+
@Override
17+
public void run() {
18+
Random generator = new Random();
19+
long waitTime = generator.nextInt(5000);
20+
boolean success = generator.nextBoolean();
21+
22+
System.out.printf("Runnable|Wait:%sms|Success:%s\n", waitTime, success);
23+
24+
try {
25+
Thread.sleep(waitTime);
26+
} catch (InterruptedException e) {
27+
e.printStackTrace();
28+
}
29+
30+
if(success) {
31+
notify.processMsg("hi");
32+
} else {
33+
notify.processMsg("bye");
34+
}
35+
}
36+
37+
});
38+
39+
try {
40+
notify.waitForMsg();
41+
} catch (InterruptedException e) {
42+
e.printStackTrace();
43+
}
44+
45+
long end = System.currentTimeMillis();
46+
47+
System.out.printf("Notify|Waited:%sms|Status:%s\n", end-start, notify.getStatus());
48+
49+
// doesn't shutdown until the run is complete
50+
service.shutdown();
51+
}
52+
53+
54+
private Status status = Status.NO_REPLY;
55+
56+
public synchronized void reset() {
57+
this.status = Status.NO_REPLY;
58+
}
59+
60+
public synchronized Status getStatus() {
61+
return status;
62+
}
63+
64+
public synchronized void processMsg(String msg) {
65+
if(msg.equals("hi")) {
66+
status = Status.SUCCESS;
67+
} else {
68+
status = Status.FAILURE;
69+
}
70+
notifyAll();
71+
}
72+
73+
public synchronized void waitForMsg() throws InterruptedException {
74+
if (status != Status.NO_REPLY) {
75+
return;
76+
}
77+
78+
wait(2000);
79+
}
80+
}
81+
82+
enum Status {
83+
SUCCESS,
84+
FAILURE,
85+
NO_REPLY;
86+
}

0 commit comments

Comments
 (0)