|
| 1 | +package com.baeldung.concurrent.phaser; |
| 2 | + |
| 3 | +import org.junit.FixMethodOrder; |
| 4 | +import org.junit.Test; |
| 5 | +import org.junit.runners.MethodSorters; |
| 6 | + |
| 7 | +import java.util.concurrent.ExecutorService; |
| 8 | +import java.util.concurrent.Executors; |
| 9 | +import java.util.concurrent.Phaser; |
| 10 | + |
| 11 | +import static junit.framework.TestCase.assertEquals; |
| 12 | + |
| 13 | +@FixMethodOrder(MethodSorters.NAME_ASCENDING) |
| 14 | +public class PhaserTest { |
| 15 | + |
| 16 | + @Test |
| 17 | + public void givenPhaser_whenCoordinateWorksBetweenThreads_thenShouldCoordinateBetweenMultiplePhases() { |
| 18 | + //given |
| 19 | + ExecutorService executorService = Executors.newCachedThreadPool(); |
| 20 | + Phaser ph = new Phaser(1); |
| 21 | + assertEquals(0, ph.getPhase()); |
| 22 | + |
| 23 | + //when |
| 24 | + executorService.submit(new LongRunningAction("thread-1", ph)); |
| 25 | + executorService.submit(new LongRunningAction("thread-2", ph)); |
| 26 | + executorService.submit(new LongRunningAction("thread-3", ph)); |
| 27 | + |
| 28 | + //then |
| 29 | + ph.arriveAndAwaitAdvance(); |
| 30 | + assertEquals(1, ph.getPhase()); |
| 31 | + |
| 32 | + //and |
| 33 | + executorService.submit(new LongRunningAction("thread-4", ph)); |
| 34 | + executorService.submit(new LongRunningAction("thread-5", ph)); |
| 35 | + ph.arriveAndAwaitAdvance(); |
| 36 | + assertEquals(2, ph.getPhase()); |
| 37 | + |
| 38 | + |
| 39 | + ph.arriveAndDeregister(); |
| 40 | + } |
| 41 | +} |
0 commit comments