In this Q&A, how threads can obtain access to limited resources in a pool using Semaphore
Conceptually Semaphore maintains permits. Threads can acquire permits or release unused permits. Thread trying to acquire a permit will wait until one is available.
See demo code below.
package com.javahowdoi.thread;
import java.util.concurrent.*;
public class SemphareDemo {
private static class SemaphoreTask implements Runnable{
Semaphore sem;
public SemaphoreTask(Semaphore sem) {
this.sem = sem;
}
@Override
public void run() {
try {
System.out.println( Thread.currentThread().getName() + " start" );
// acquire a permit
sem.acquire();
Thread.sleep(1000);
System.out.println( Thread.currentThread().getName() + " done" );
} catch (InterruptedException e) {
e.printStackTrace();
}
finally {
sem.release();
}
}
}
public static void main(String[] args ) throws InterruptedException {
// 5 threads competing for two resources
Semaphore se = new Semaphore(2);
ExecutorService es = Executors.newFixedThreadPool(5);
for(int i = 0; i < 5; ++i) {
es.submit( new SemaphoreTask(se));
}
es.shutdown();
}
}
Comments
Post a Comment