Skip to content

Commit df4c182

Browse files
committed
Add code for module 1, part 5, video 2
1 parent fbe3ee5 commit df4c182

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
void main() {
2+
3+
4+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import java.util.concurrent.CopyOnWriteArrayList;
2+
import java.util.concurrent.ThreadLocalRandom;
3+
import java.util.function.Consumer;
4+
5+
void main() throws InterruptedException {
6+
Consumer<String> observer1 = string -> System.out.println("observer 1 observed: " + string);
7+
Consumer<String> observer2 = string -> System.out.println("observer 2 observed: " + string);
8+
Consumer<String> observer3 = string -> System.out.println("observer 3 observed: " + string);
9+
10+
var subject = new CopyOnWriteArrayList<Consumer<String>>();
11+
subject.add(observer1);
12+
subject.add(observer2);
13+
subject.add(observer3);
14+
15+
Thread.startVirtualThread(() -> {
16+
int counter = 3;
17+
while (true) {
18+
int observerId = ++counter;
19+
Consumer<String> observer = string -> System.out.println("observer " + observerId + " observed: " + string);
20+
subject.add(observer);
21+
sleepLong();
22+
}
23+
});
24+
25+
Thread.startVirtualThread(() -> {
26+
while (true) {
27+
subject.removeFirst();
28+
sleepLong();
29+
}
30+
});
31+
32+
while (true) {
33+
subject.forEach(observer -> observer.accept("message"));
34+
System.out.println();
35+
Thread.sleep(500);
36+
}
37+
}
38+
39+
private static void sleepLong() {
40+
try {
41+
Thread.sleep(ThreadLocalRandom.current().nextInt(1500, 2500));
42+
} catch (InterruptedException e) {
43+
throw new RuntimeException(e);
44+
}
45+
}

0 commit comments

Comments
 (0)