From aab95f0bd68cb09738ef4c836ea8925a97652f26 Mon Sep 17 00:00:00 2001 From: zkhut16 Date: Wed, 24 Feb 2021 13:31:44 +0400 Subject: [PATCH] implemented my version of CountDownLatch using Semaphore --- Java2020/src/homework/MyCountDownLatch.java | 28 +++++++++++++++++ .../src/homework/MyCountDownLatchExample.java | 30 +++++++++++++++++++ 2 files changed, 58 insertions(+) create mode 100644 Java2020/src/homework/MyCountDownLatch.java create mode 100644 Java2020/src/homework/MyCountDownLatchExample.java diff --git a/Java2020/src/homework/MyCountDownLatch.java b/Java2020/src/homework/MyCountDownLatch.java new file mode 100644 index 0000000..874c9cb --- /dev/null +++ b/Java2020/src/homework/MyCountDownLatch.java @@ -0,0 +1,28 @@ +package homework; + +import java.util.concurrent.Semaphore; +import java.util.concurrent.atomic.AtomicInteger; + +public class MyCountDownLatch { + private AtomicInteger count; + Semaphore blocker; + public MyCountDownLatch(int count){ + this.count = new AtomicInteger(count); + blocker = new Semaphore(0); + } + + public void await(){ + if(count.get() > 0) + blocker.acquireUninterruptibly(); + } + + public void countDown(){ + if(count.decrementAndGet() == 0) { + blocker.release(2 * blocker.getQueueLength()); + } + } + + public long getCount(){ + return count.get(); + } +} diff --git a/Java2020/src/homework/MyCountDownLatchExample.java b/Java2020/src/homework/MyCountDownLatchExample.java new file mode 100644 index 0000000..80b428e --- /dev/null +++ b/Java2020/src/homework/MyCountDownLatchExample.java @@ -0,0 +1,30 @@ +package homework; + + +public class MyCountDownLatchExample { + public static void main(String[] args) { + MyCountDownLatch mcdl = new MyCountDownLatch(5); + for(int i = 10; i > 0; i--){ + new Thread(()->{ + mcdl.await(); + System.out.println("do something" + Thread.currentThread()); + }).start(); + } + for(int i = 0; i < 6; i++){ + try { + Thread.sleep(1000); + mcdl.countDown(); + System.out.println("iteration #"+(i+1)); + System.out.println("count : "+mcdl.getCount()); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + for(int i = 10; i > 0; i--){ + new Thread(()->{ + mcdl.await(); + System.out.println("do something" + Thread.currentThread()); + }).start(); + } + } +}