2010-09-05 67 views
2

停止线程并等待某个语句(或方法)被另一个线程执行一定次数的最佳方法是什么? 我在想这样的事(让“数字”是一个int):java:等到另一个线程执行n次语句

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

... 

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

显然,这是行不通的,首先是因为它似乎你不能等待()上的int类型。此外,所有其他解决方案都来自我的java天真头脑,对于这样一个简单的任务来说非常复杂。有什么建议么? (谢谢!)

回答

6

听起来就像你正在寻找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 

一个Semaphore也将工作:

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 
+0

信号量似乎只是在这里,感谢! – etuardu 2010-09-05 19:52:55