-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathBusyWaitGood.java
More file actions
43 lines (40 loc) · 1.15 KB
/
BusyWaitGood.java
File metadata and controls
43 lines (40 loc) · 1.15 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
class Message {
public String text = "";
}
class Receiver implements Runnable {
private Message message;
public Receiver(Message msg) {
this.message = msg;
}
public void run() {
synchronized(message) {
while(message.text.isEmpty()) {
try {
message.wait(); // Wait for a notification
} catch (InterruptedException e) { }
}
}
System.out.println("Message Received at " + (System.currentTimeMillis()/1000));
System.out.println(message.text);
}
}
class Sender implements Runnable {
private Message message;
public Sender(Message msg) {
this.message = msg;
}
public void run() {
System.out.println("Message sent at " + (System.currentTimeMillis()/1000));
synchronized(message) {
message.text = "Hello World";
message.notifyAll(); // Send notification
}
}
}
public class BusyWait {
public static void main(String[] args) {
Message msg = new Message();
new Thread(new Receiver(msg)).start();
new Thread(new Sender(msg)).start();
}
}