Java共享锁 模拟应用场景

tech2026-01-06  4

package com.mgk.threads.shared; import java.util.concurrent.Semaphore; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; /** * 共享锁 * Semaphore(int num) * num 参数含义,允许多个线程共同运行。只有当之前的线程释放后,后续的线程还才可运行。 * */ public class TestThread { public static void main(String[] args) { Semaphore semaphore = new Semaphore(2); Lock lock = new ReentrantLock(); new Thread( new ThreadA(semaphore,lock),"qx").start(); new Thread( new ThreadA(semaphore,lock),"sc").start(); new Thread( new ThreadA(semaphore,lock),"gk").start(); } } class ThreadA implements Runnable{ private volatile static int count = 2; private Lock lock; private Semaphore semaphore ; public ThreadA(Semaphore semaphore, Lock lock){ this.semaphore = semaphore; this.lock=lock; } private int get(){ this.lock.lock(); try { return --count; }finally { this.lock.unlock(); } } private int exit(){ this.lock.lock(); try { return ++count; }finally { this.lock.unlock(); } } @Override public void run() { try { this.semaphore.acquire(); System.out.println(Thread.currentThread().getName() +"进入停车厂,剩余车位:" + get()); Thread.sleep(2000); System.out.println(Thread.currentThread().getName() +"出入停车厂,剩余车位:" + exit()); } catch (InterruptedException e) { e.printStackTrace(); }finally { semaphore.release(); } } }

停车场就两个停车位 也就是只能允许两个线程进去然后争夺锁钥匙停车 当有车出去后,空出停车场位置,下一辆车才允许进来

 

 

如果不释放锁会一直阻塞状态

最新回复(0)