Skip to content

Instantly share code, notes, and snippets.

@greekykhs
Created July 4, 2022 07:46
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
final class Task implements Runnable
{
private int taskId;
private Semaphore semaphore;
public Task(int taskId, Semaphore semaphore)
{
this.taskId=taskId;
this.semaphore=semaphore;
}
@Override
public void run() {
System.out.println("Running a thread with name :"+Thread.currentThread().getName()+", for task id:"+this.taskId);
try {
semaphore.acquire();
//call slow service
slowService();
semaphore.release();
}
catch(InterruptedException e){}
}
public void slowService() throws InterruptedException
{
Thread.sleep(100);
}
}
public class SemaphoreTest {
public static void main(String[] args) {
try {
//5 is the number of Permits
Semaphore semaphore= new Semaphore(5);
ExecutorService exeService=Executors.newFixedThreadPool(50);
//IntStream.of(1000).forEach(i->exeService.submit(new Task(i, semaphore)));
for (int i=0; i<100;i++){
exeService.submit(new Task(i, semaphore));
}
exeService.shutdown();
exeService.awaitTermination(1, TimeUnit.MINUTES);
}
catch(InterruptedException e){}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment