Skip to content

Instantly share code, notes, and snippets.

@adohe-zz
Created January 11, 2015 03:40
Show Gist options
  • Save adohe-zz/19323838f0f1b0f24c52 to your computer and use it in GitHub Desktop.
Save adohe-zz/19323838f0f1b0f24c52 to your computer and use it in GitHub Desktop.
Simple about CountLatch usage
package com.xqbase.java;
import java.util.concurrent.CountDownLatch;
/**
* Simple about how to use Latch {@link java.util.concurrent.CountDownLatch}
* to control the threads start&stop process.
*
* @author Tony He
*/
public class TestHarness {
private static 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() {
@Override
public void run() {
try {
startGate.await();
try {
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored) {}
}
};
t.start();
}
long start = System.nanoTime();
startGate.countDown();
endGate.await();
long end = System.nanoTime();
return end - start;
}
public static void main(String[] args) throws InterruptedException {
final Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("Task start...");
// do some task
System.out.println("Task end...");
}
};
System.out.println(timeTasks(5, runnable));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment