2012-05-08 52 views
12

的变化是有没有办法等待一个AtomicInteger,这样我就不必继续睡我的当前线程和保持检查的AtomicInteger这样有没有一种方法,以等待在原子整数

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

我知道有这样的事,作为一个CountDownLatch但只允许我减我还需要它能够增加

而且背景故事 - 我有一个循环创建线程,我需要等待一个在创建新线程之前完成线程的执行。我正在使用一个Executors.newFixedThreadPool(numThreads),并且等待它的唯一方法似乎是调用shutdown方法等待终止,然后创建一个新的threadPool,所以我使用原子整数来跟踪有多少个线程正在运行和/或在队列中,这样当数量减少时,我可以继续循环。

+6

简短的回答是否定的。你可以编辑你的问题,并解释多一点_why_你想要这个?可能有其他选择。 – Gray

+0

为什么不使用WaitForSingleObject进行等待。创建一个while循环来等待是一个可怕的想法。 – CyprUS

+4

等待一个原子对象完全失败了等待算法的目的。你这样做是错的。 – maerics

回答

2

我想你真正想要的是处理一些事件。该事件又可以增加一个整数。看一眼BlockingQueue

一个队列,它额外支持在检索元素时等待队列变为非空操作并在存储元素时等待队列中的空间变为可用的操作。

的代码可能看起来像......

MyEvent incrementEvent = queue.take(); //blocks until an event is added to the queue 
// increment int and do logic here 
6

Semaphore看起来似乎更接近你要找的东西,实际上 - 它可以让你等到一个或多个“许可证“可用。 AtomicInteger并不意味着如何使用它。

0

如果您使用的是Executors API,等待任务完成的正确方法是使用Future API。示例代码如下所示:

Future<?> future = threadPool.submit(task); 
future.get(); 
0

我认为您想要的更接近匹配的是Phaser。我的粗略理解是,它有点像一个递增计数器,你可以阻止它,直到数字增加。

// This constructor one party (so it expects one advance per phase). 
Phaser phaser = new Phaser(1); 
try { 
    // This will timeout as phase 0 hasn't arrived yet. 
    phaser.awaitAdvanceInterruptibly(0, 1, TimeUnit.MILLISECONDS); 
    fail(); 
} 
catch (TimeoutException expected) { 
} 

// Arrive phase 0 
phaser.arrive(); 
phaser.awaitAdvance(0); 
try { 
    // Phase 1 will timeout.. 
    phaser.awaitAdvanceInterruptibly(1, 1, TimeUnit.MILLISECONDS); 
    fail(); 
} 
catch (TimeoutException expected) { 
} 

// Arrive phase 1 
phaser.arrive(); 
phaser.awaitAdvance(0); 
phaser.awaitAdvance(1); 
相关问题