public class SemaphoreLock {
private final Semaphore semaphore = new Semaphore(1);
public void lock() throws InterruptedException {
semaphore.acquire();
}
public void unlock(){
semaphore.release();
}
public static void main(String[] args) {
SemaphoreLock lock = new SemaphoreLock();
for(int i=0; i<2; i++){
new Thread(()->{
try {
System.out.println(Thread.currentThread().getName() + " is running ");
lock.lock();
System.out.println(Thread.currentThread().getName() + " get the lock ");
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
System.out.println(Thread.currentThread().getName() + " release the lock ");
}).start();
}
}
}