Created
January 27, 2025 08:09
-
-
Save omidp/abd65374db949a1b6d8f718ac83bb0a3 to your computer and use it in GitHub Desktop.
Run in multiple threads for tests
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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