使特定线程等待,直到计数器达到0

时间:2019-10-05 11:26:23

标签: java multithreading

我正在尝试使某些线程使用相同的参数块调用该函数,直到该函数返回0。每个线程都递减一个计数器,然后检查它是否为0。我将如何做呢? / p>

我尝试研究wait / notifyAll,但不确定如何使其正常工作。我无法弄清楚如何仅通知正在等待相同参数的特定线程,尤其是当我有两组线程在两个不同的计数器上等待其参数时。

我正在使用带有ReentrantReadWriteLock的哈希图,该哈希图将参数与其计数器配对。

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();
    }
}

2 个答案:

答案 0 :(得分:0)

您将需要使用同步键盘。这是类似的问题is there a 'block until condition becomes true' function in java?

这里是代码供您参考

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();
    }
}

希望您会发现它对您有帮助。

答案 1 :(得分:0)

您可以尝试以下操作:

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

   //things what this thread need to do
}