views:

55

answers:

2

Hi, what is the best way to stop a thread and wait for a statement (or a method) to be executed a certain number of times by another thread? I was thinking about something like this (let "number" be an int):

number = 5;
while (number > 0) {
   synchronized(number) { number.wait(); }
}

...

synchronized(number) {
   number--;
   number.notify();
}

Obviously this wouldn't work, first of all because it seems you can't wait() on a int type. Furthermore, all other solutions that come to my java-naive mind are really complicated for such a simple task. Any suggestions? (Thanks!)

+5  A: 

Sounds like you're looking for CountDownLatch.

CountDownLatch latch = new CountDownLatch(5);
...
latch.await(); // Possibly put timeout


// Other thread... in a loop
latch.countDown(); // When this has executed 5 times, first thread will unblock

A Semaphore would also work:

Semaphore semaphore = new Semaphore(0);
...
semaphore.acquire(5);

// Other thread... in a loop
semaphore.release(); // When this has executed 5 times, first thread will unblock
Jon Skeet
A semaphore seems just natty here, thanks!
etuardu
+2  A: 

You might find something like a CountDownLatch useful.

Steven Schlansker