Skip to content

Instantly share code, notes, and snippets.

@omidp
Created January 27, 2025 08:09
Show Gist options
  • Save omidp/abd65374db949a1b6d8f718ac83bb0a3 to your computer and use it in GitHub Desktop.
Save omidp/abd65374db949a1b6d8f718ac83bb0a3 to your computer and use it in GitHub Desktop.
Run in multiple threads for tests
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Run in multiple threads.
*/
public class RunInThreads {
private final int numberOfThreads;
public RunInThreads(int numberOfThreads) {
this.numberOfThreads = numberOfThreads;
}
public void run(Runnable runnable) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(numberOfThreads);
ExecutorService executorService = Executors.newFixedThreadPool(numberOfThreads);
for (long i = 1; i <= numberOfThreads; i++) {
executorService.execute(() -> {
runnable.run();
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment