11package com .baeldung .concurrent .countdownlatch ;
22
3- import org .assertj .core .api .Assertions ;
43import org .junit .Test ;
54
65import java .util .ArrayList ;
76import java .util .Collections ;
87import java .util .List ;
98import java .util .concurrent .CountDownLatch ;
109import java .util .concurrent .TimeUnit ;
11- import java .util .concurrent .TimeoutException ;
1210import java .util .stream .Stream ;
1311
1412import static java .util .stream .Collectors .toList ;
1715public class CountdownLatchExampleTest {
1816 @ Test
1917 public void whenParallelProcessing_thenMainThreadWillBlockUntilCompletion () throws InterruptedException {
20-
2118 // Given
2219 List <String > outputScraper = Collections .synchronizedList (new ArrayList <>());
2320 CountDownLatch countDownLatch = new CountDownLatch (5 );
@@ -59,6 +56,41 @@ public void whenFailingToParallelProcess_thenMainThreadShouldTimeout() throws In
5956 final boolean result = countDownLatch .await (3L , TimeUnit .SECONDS );
6057
6158 // Then
62- assertThat (result ).isTrue ();
59+ assertThat (result ).isFalse ();
60+ }
61+
62+ @ Test
63+ public void whenDoingLotsOfThreadsInParallel_thenStartThemAtTheSameTime () throws InterruptedException {
64+ // Given
65+ List <String > outputScraper = Collections .synchronizedList (new ArrayList <>());
66+ CountDownLatch readyThreadCounter = new CountDownLatch (5 );
67+ CountDownLatch callingThreadBlocker = new CountDownLatch (1 );
68+ CountDownLatch completedThreadCounter = new CountDownLatch (5 );
69+ List <Thread > workers = Stream
70+ .generate (() -> new Thread (new WaitingWorker (outputScraper , readyThreadCounter , callingThreadBlocker , completedThreadCounter )))
71+ .limit (5 )
72+ .collect (toList ());
73+
74+ // When
75+ workers .forEach (Thread ::start );
76+ readyThreadCounter .await (); // Block until workers start
77+ outputScraper .add ("Workers ready" );
78+ callingThreadBlocker .countDown (); // Start workers
79+ completedThreadCounter .await (); // Block until workers finish
80+ outputScraper .add ("Workers complete" );
81+
82+ // Then
83+ outputScraper .forEach (Object ::toString );
84+ assertThat (outputScraper )
85+ .containsExactly (
86+ "Workers ready" ,
87+ "Counted down" ,
88+ "Counted down" ,
89+ "Counted down" ,
90+ "Counted down" ,
91+ "Counted down" ,
92+ "Workers complete"
93+ );
6394 }
95+
6496}
0 commit comments