달력

2

« 2025/2 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
2011. 8. 27. 16:04

CountDownLatch JAVA이야기2011. 8. 27. 16:04

CountDownLatch startGate = new CountDownLatch(nThreads); //nThread가 0이되면 latch가 열림

startGate.countDown() 메소드는 startGate를 생성했을 때 사용했던 인자의 값을 1 감소시킨다. (nThreads = nThreads-1)
startGate.await() 메소드는 nThreads가 0이 될 때까지 대기를 한다.

public long timeTasks(int nThreads, final Runnable task) throws InterruptedException{
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i = 0; i < nThreads; i++) {
Thread t = new Thread(){
public void run() {
try {
startGate.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
task.run();
}finally{
endGate.countDown();
}
};
};
t.start();
}
long start = System.nanoTime();
startGate.countDown(); //0이 되었으므로 래치가 열림 for문의 스레드들이 동작한다.
endGate.await();         //스레드들의 작업이 모두 마칠때까지 대기.. nThreads가 0이되기를 기다림
long end = System.nanoTime();
return end-start;
}
/* 시스템의 구동되는 전체 시간을 구할 수 있다 */ 

'JAVA이야기' 카테고리의 다른 글

Barrier  (0) 2011.08.28
futureTask  (0) 2011.08.27
반복문을 실행하는 코드를 동기화시키는 방법은 비효율적이다.  (0) 2011.08.27
AppLevel에서 바인딩 변수 사용하기  (0) 2011.08.23
IBM의 JIT Compiler  (0) 2011.08.21
:
Posted by НooпeУ


Code Start Code End