How to Use Semaphore in Java


In following example, we can get the method to use Semaphore in Java.

Source Code

package com.beginner.examples;

import java.util.concurrent.*;

public class SemaphoreExample {
    // new Semaphore
	private static final Semaphore semaphore = new Semaphore(4);
	private static final ThreadPoolExecutor pool = new ThreadPoolExecutor(6, 10, 50, TimeUnit.SECONDS, new LinkedBlockingQueue());
	
	private static class RunThread extends Thread{
		
		public void run()
		{
			try
			{
				//acquire semaphore
                semaphore.acquire();
				System.out.println(Thread.currentThread().getName() + " ,time: " + System.currentTimeMillis());
                //sleep 2000
				Thread.sleep(2000);
				semaphore.release();
				
			}
			catch(InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args)
	{
		for(int i = 0; i < 10; i++)
		{
			// new RunThread
            Thread r = new RunThread();
			pool.execute(r);
		}
	}
 
}

Output:

pool-1-thread-1 ,time: 1561713802053
pool-1-thread-3 ,time: 1561713802053
pool-1-thread-2 ,time: 1561713802053
pool-1-thread-5 ,time: 1561713802053
pool-1-thread-1 ,time: 1561713804053
pool-1-thread-2 ,time: 1561713804054
pool-1-thread-5 ,time: 1561713804054
pool-1-thread-4 ,time: 1561713804055
pool-1-thread-6 ,time: 1561713806054
pool-1-thread-3 ,time: 1561713806054
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments