forked from janbodnar/Java-Advanced
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageSender.java
More file actions
78 lines (52 loc) · 1.57 KB
/
MessageSender.java
File metadata and controls
78 lines (52 loc) · 1.57 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.zetcode;
import java.time.LocalTime;
class MessageSender {
public void send(String msg) {
var now = LocalTime.now();
System.out.printf("Sending message, %s%n", now);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.printf("%s sent%n", msg);
}
}
class Worker extends Thread {
private String msg;
private final MessageSender messageSender;
public Worker(String msg, MessageSender messageSender) {
this.msg = msg;
this.messageSender = messageSender;
}
public void run() {
// Only one thread can send a message
// at a time.
synchronized (messageSender) {
messageSender.send(msg);
}
}
}
public class SynchronizedMessages {
public static void main(String[] args) {
var snd = new MessageSender();
var w1 = new Worker("Hello there", snd);
var w2 = new Worker("New mail received", snd);
var w3 = new Worker("Notes taken", snd);
// start three threads
w1.start();
w2.start();
w3.start();
// wait for threads to end
try {
// join is a blocker method which waits for a thread to complete.
// the w1.join() causes the current thread to pause execution
// until w1's thread terminates.
w1.join();
w2.join();
w3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}