Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Zura Khutsishvili - implemented my version of CountDownLatch using Semaphore #20

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Java2020/src/homework/MyCountDownLatch.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
30 changes: 30 additions & 0 deletions Java2020/src/homework/MyCountDownLatchExample.java
Original file line number Diff line number Diff line change
@@ -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();
}
}
}