2010-09-05 65 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