Indeed, multiple-thread program helps improve the performance of the application. One of the best ways to test if the performance is really improved is the execution time.
In Java, System.currentTimeMillis(); is usually used to calculate the execution time of a code block.long startTime = System.currentTimeMillis();
<code block here>
long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
But if the code block contains multiple threads inside then this calculation is not true. Usually, the elapsedTime will be calculated before the longest thread completed, as a result, the elapsedTime will be incorrectly calculated.
To cope with this problem, CountDownLatch is a simple tool to be used. The general idea is that this object will set a countdown number, called stopWatch, equal to the number of threads. In run() function of each thread, stopLatch is coutdowned. Outside of the code block, stopWatch calls await function, which mean that the main thread will wait until all other subthreads has been completed (based on the stopWatch equal to 0). Then the elapse time is calculated.
CountDownLatch stopLatch= new CountDownLatch(18);long startTime = System.currentTimeMillis();<code block here>stopLatch.await();long stopTime = System.currentTimeMillis();
long elapsedTime = stopTime - startTime;
Run function:
public void run() {
try {
}
finally{
stopLatch.countDown();
}
}
Comments
Post a Comment