有没有办法等待原子整数的变化 [英] Is there a way to wait for the change on an atomic integer

查看:87
本文介绍了有没有办法等待原子整数的变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法等待AtomicInteger,这样我就不必一直休眠当前线程并像这样继续检查AtomicInteger

Is there a way to wait on an AtomicInteger so that I don't have to keep sleeping my current thread and keep checking on the AtomicInteger like this

while(atomicInt.get() >= 0) {
    Thread.sleep(1000)
}

我知道有一个CountDownLatch之类的东西,但这只允许我递减,我还需要它能够递增

I know there is such a thing as a CountDownLatch but that only allows me to decrement I also need it to be able to increment

进一步的故事- 我有一个创建线程的循环,我需要等待其中一个线程执行完成才能创建新线程.但是,我正在使用Executors.newFixedThreadPool(numThreads),等待它的唯一方法似乎是调用shutdown方法await终止,然后创建一个新的threadPool,所以我改用原子整数来跟踪正在运行的线程数和/或排队,以便当该数量减少时,我可以继续循环.

Further BackStory - I have a loop creating threads and I need to wait on one of the threads execution to finish before creating a new thread. I however am using an Executors.newFixedThreadPool(numThreads) and the only way to wait on it seems to be to call the shutdown method await termination and then create a new threadPool so instead I was using an atomic integer to keep track of how many threads were running and/or on the queue so that when that number decreased I could continue with the loop.

推荐答案

AtomicInteger并不意味着您将如何使用它.

Semaphore looks like it might be closer to what you're looking for, actually -- it lets you wait until one or more "permits" is available. AtomicInteger isn't meant to be used how you're using it.

这篇关于有没有办法等待原子整数的变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆