-1

I'm trying to make certain threads that call a function with the same parameter block until the function returns a 0. Each thread decrements a counter and then check if it's a 0. How would i go on about doing that?

I've tried looking into wait/notifyAll but I'm not sure how to make it work properly. I cant figure out how to notify only specific threads that are waiting on the same parameter, especially if I have 2 sets of threads waiting on two different counters for their parameters.

I'm using a hashmap with a ReentrantReadWriteLock that pairs the parameter with its counter.

count.decreaseCount(s);
while (count.getCount(s) != 0) {
    try {
        Thread.currentThread().wait();
    } catch (InterruptedException e) {
        System.out.println("Thread " + threadNo + "is waiting.");
        Thread.currentThread().interrupt();
    }
}
imaretard
  • 1
  • 1
  • 1
    Your requirement is not clear. Please elaborate it properly. Check this out and post a minimal, reproducible example: https://stackoverflow.com/help/minimal-reproducible-example – Ravindra Ranwala Oct 05 '19 at 12:52

2 Answers2

0

You will need to use synchronized keyboard. Here is similar question is there a 'block until condition becomes true' function in java?.

Here is a code for your reference

public class VolatileData {

    public static class Counter {

        int counter = 10;

        public int getCounter() {
            return counter;
        }

        public void decrement() {
            --counter;
        }

    }

    public static void main(String[] args) {
        Counter counter = new Counter();
        Thread t1 = new Thread() {
            @Override
            public void run() {
                synchronized (counter) {
                    try {
                        counter.wait(); //this will wait until another thread calls counter.notify
                    } catch (InterruptedException ex) {
                    }
                    System.out.println("Wait Complted");
                }
            }
        };
        Thread t2 = new Thread() {
            @Override
            public void run() {
                synchronized (counter) {
                    while (counter.getCounter() != 0) {
                        counter.decrement();
                        try {
                            System.out.println("Decrement Counter");
                            Thread.sleep(100);
                        } catch (InterruptedException ex) {
                        }
                    }
                    counter.notify(); //notify another thread after counter become 0
                }
            }

        };
        t1.start();
        t2.start();
    }
}

I hope you will find it helpful.

Kshitij Dhakal
  • 816
  • 12
  • 24
0

You can try something like this:

public void run(){
   count.decreaseCount(s);
   while (count.getCount(s) != 0);

   //things what this thread need to do
}
Bogus
  • 283
  • 1
  • 2
  • 13