Limit the number of concurrent accesses to concurrent resources. samephore.acquire(); acquires a license samephore.release(); releases a license.
public class SemaphoreTest implements Runnable { Semaphore samephore; int id; public SemaphoreTest(Semaphore samephore, int id) { this.samephore = samephore; this.id = id; } @Override public void run() { // TODO Auto-generated method stub try { samephore.acquire(); Thread.sleep(1000); System.out.println( "Customer ID" + id + "Task being processed" ); samephore.release(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { Semaphore samephore = new Semaphore(10, true ); // Limit the number of concurrent accesses to 10 true to use fair mode. advanced first traversal for ( int i = 0; i < 20; i++ ) { new Thread( new SemaphoreTest(samephore, i)).start();; } } }
Simulate 10 windows for handling tasks in a bank. samephore.acquire() If there are 10 tasks that have obtained permission and have not been released, others are waiting for a task that is executing permission to release the permission to enter