How to allow multiple threads concurrently access the shared data?
Semaphore
- It maintains the no. of permits to access the shared resource. If the no. of permits are 2, then 2 threads can access the shared resource simultaneously without getting blocked.
- A thread which needs access to the shared resource must acquire a permit by calling acquire()
- If the no. of permits are exhausted, then the thread gets blocked until one of the permits is released by another thread
- permit can be released by calling the release() method.
In this example, at any given pt of time, only 2 threads can access the shared thread simultaneously
public class SemaphoreExample { Semaphore semaphore = new Semaphore(2); public static void main(String[] args) { SemaphoreExample semaphoreInstance = new SemaphoreExample(); new Thread(()->{ semaphoreInstance.mutualExclusion(); }, "THREAD-1").start(); new Thread(()->{ semaphoreInstance.mutualExclusion(); }, "THREAD-2").start(); new Thread(()->{ semaphoreInstance.mutualExclusion(); }, "THREAD-3").start(); new Thread(()->{ semaphoreInstance.mutualExclusion(); }, "THREAD-4").start(); } private void mutualExclusion(){ try{ semaphore.acquire(); System.out.println(Thread.currentThread().getName()+" accessing shared resource"); Thread.sleep(1000); }catch(InterruptedException e){ e.printStackTrace(); }finally { semaphore.release(); System.out.println(Thread.currentThread().getName()+" released shared resource"); } } } Output THREAD-3 accessing shared resource THREAD-1 accessing shared resource THREAD-3 released shared resource THREAD-4 accessing shared resource THREAD-1 released shared resource THREAD-2 accessing shared resource THREAD-2 released shared resource THREAD-4 released shared resource
Comments
Post a Comment