Item 81. Concurrent Utilities
๋๊ธฐํ ์ฅ์น๋ฅผ ์ฌ์ฉํ ์์
import java.util.concurrent.CountDownLatch;
public class Test {
// ๋์๋ค์ ๋์์ ์์ํด ๋ชจ๋ ์๋ฃํ๋ ๋ฐ ๊ฑธ๋ฆฌ๋ ์๊ฐ์ ์ธก์ ํ๋ ๋ฉ์๋
public static long time(Executor executor, int concurrency, Runnable action)
throws InterruptedException {
CountDownLatch ready = new CountDownLatch(concurrency);
CountDownLatch start = new CountDownLatch(1);
CountDownLatch done = new CountDownLatch(concurrency);
for (int i = 0; i < concurrency; i++) {
// concurrency๋งํผ ์์
์ ์ค๋ ๋๋ฅผ ์์ฑ
executor.execute(() -> {
// ํ์ด๋จธ์ ์ค๋น ์๋ฃ ์ ํธ๋ฅผ ๋ณด๋
ready.countDown();
try {
// ๋ชจ๋ ์์
์ ์ค๋ ๋๊ฐ ์ค๋น๋ ๋๊น์ง ๊ธฐ๋ค๋ฆผ
start.await();
action.run();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
// ํ์ด๋จธ์ ์์
์๋ฃ ์ ํธ๋ฅผ ๋ณด๋
done.countDown();
}
});
}
ready.await(); // ๋ชจ๋ ์์
์๊ฐ ์ค๋น๋ ๋๊น์ง ๊ธฐ๋ค๋ฆผ
long startNanos = System.nanoTime();
start.countDown(); // ์์
์๋ค์ ๊นจ์
done.await(); // ๋ชจ๋ ์์
์๊ฐ ์์
์ ์๋ฃํ ๋๊น์ง ๊ธฐ๋ค๋ฆผ
return System.nanoTime() - startNanos;
// nanoTime์ด currentTimesMillis๋ณด๋ค ๋ ์ ํํ๊ณ , ์์คํ
์ ์ค์๊ฐ ์๊ณ ์๊ฐ ๋ณด์ ์ ์ํฅ์ ๋ฐ์ง ์์
}
}wait์ notify
wait์ notifyLast updated