Explaining Semaphore by example
This post helps to explore more into java.util.concurrent package. It explains java.util.concurrent.Semaphore class with example. Many time while developing multi threaded application , we may have multiple threads accessing particular system resource concurrently. If you want to limit no of open request for the resource then Semaphore is the option available in java. Limiting no of open request we can improve throughout of a systemn. Using Semaphore we can control no of running thread at a time out of all available running threads. Following example explains using Semaphore 1: import java.util.*; 2: import java.util.concurrent.*; 3: class SemaphoreTest 4: { 5: public static void main(String[] args) 6: { 7: // Limiting No on threads running to 2 8: Semaphore semaphore = new Semaphore(2); 9: for ( int i=0 ;i<5;i++){ 10: new MyThread(String.valueOf(i),semaphore).start(); 11: } 12: ...