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(); } } }
使用semaphore写一个显示锁
猜你喜欢
转载自www.cnblogs.com/moris5013/p/11876794.html
今日推荐
周排行