File tree Expand file tree Collapse file tree 2 files changed +49
-0
lines changed
src/main/java/eu/happycoders/datastructures/module2/p5_thread_safe_lists/v02_copyonwritearraylist Expand file tree Collapse file tree 2 files changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ void main () {
2
+
3
+
4
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments