Posts

Showing posts from September, 2017

Java Thread – Mutex and Semaphore example

Java multi threads example to show you how to use Semaphore and Mutex to limit the number of threads to access resources. Semaphores – Restrict the number of threads that can access a resource. Example, limit max 10 connections to access a file simultaneously. Mutex – Only one thread to access a resource at once. Example, when a client is accessing a file, no one else should have access the same file at the same time. 1. Semaphore Consider an ATM cubicle with 4 ATMs, Semaphore can make sure only 4 people can access simultaneously. import java.util.concurrent.Semaphore; import java.util.stream.IntStream; /** * * @author Amila Silva * */ public class SemaphorTest { // max 4 people static Semaphore semaphore = new Semaphore(4); static class ATMThread extends Thread { String name = ""; public ATMThread(String name) { this.name = name; } public void run() { try { System.out.println(name + " acquiring lock..."); Syste