|
| 1 | +package barrier; |
| 2 | + |
| 3 | +import org.junit.Test; |
| 4 | +import org.junit.jupiter.api.Assertions; |
| 5 | + |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | + |
| 9 | +public class TestCountDownLatch { |
| 10 | + |
| 11 | + @Test |
| 12 | + public void testCountDown() throws InterruptedException { |
| 13 | + int threadCount = 10, diff = 4; |
| 14 | + CountDownLatch latchSingleThread = new CountDownLatch(threadCount); |
| 15 | + Assertions.assertEquals(threadCount, latchSingleThread.getCount()); |
| 16 | + latchSingleThread.countDown(); |
| 17 | + latchSingleThread.countDown(); |
| 18 | + Assertions.assertEquals(threadCount-2, latchSingleThread.getCount()); |
| 19 | + CountDownLatch latch = new CountDownLatch(threadCount); |
| 20 | + java.util.concurrent.CountDownLatch realLatch = new |
| 21 | + java.util.concurrent.CountDownLatch(threadCount - diff); |
| 22 | + ExecutorService service = Executors.newFixedThreadPool(10); |
| 23 | + for (int i = 0; i < threadCount; i++) { |
| 24 | + service.submit(() -> { |
| 25 | + try { |
| 26 | + Thread.sleep(1000); |
| 27 | + } catch (InterruptedException e) { |
| 28 | + e.printStackTrace(); |
| 29 | + } |
| 30 | + latch.countDown(); |
| 31 | + realLatch.countDown(); |
| 32 | + }); |
| 33 | + } |
| 34 | + realLatch.await(); |
| 35 | + Assertions.assertEquals(diff, latch.getCount()); |
| 36 | + } |
| 37 | + |
| 38 | + |
| 39 | + @Test |
| 40 | + public void testAwait() throws InterruptedException { |
| 41 | + CountDownLatch latch = new CountDownLatch(3); |
| 42 | + Thread t1 = new Thread(() -> { |
| 43 | + try { |
| 44 | + Thread.sleep(1000); |
| 45 | + latch.countDown(); |
| 46 | + } catch (InterruptedException e) { |
| 47 | + e.printStackTrace(); |
| 48 | + } |
| 49 | + }); |
| 50 | + Thread t2 = new Thread(() -> { |
| 51 | + try { |
| 52 | + Thread.sleep(1000); |
| 53 | + latch.countDown(); |
| 54 | + } catch (InterruptedException e) { |
| 55 | + e.printStackTrace(); |
| 56 | + } |
| 57 | + }); |
| 58 | + Thread t3 = new Thread(() -> { |
| 59 | + try { |
| 60 | + Thread.sleep(1000); |
| 61 | + latch.countDown(); |
| 62 | + } catch (InterruptedException e) { |
| 63 | + e.printStackTrace(); |
| 64 | + } |
| 65 | + }); |
| 66 | + t1.start(); |
| 67 | + t2.start(); |
| 68 | + t3.start(); |
| 69 | + |
| 70 | + latch.await(); |
| 71 | + Assertions.assertEquals(0, latch.getCount()); |
| 72 | + Assertions.assertEquals(Thread.State.TERMINATED, t1.getState()); |
| 73 | + Assertions.assertEquals(Thread.State.TERMINATED, t2.getState()); |
| 74 | + Assertions.assertEquals(Thread.State.TERMINATED, t3.getState()); |
| 75 | + |
| 76 | + } |
| 77 | + |
| 78 | + |
| 79 | +} |
0 commit comments