1public class MyThreadTest { 2 private final static Semaphore semaphore = new Semaphore(2);// 设置2个车位 3 4 public static void main(String[] args) { 5 System.out.println("start"); 6 7 p(semaphore, true, 1); 8 p(semaphore, false, 2); 9 p(semaphore, false, 3); 10 p(semaphore, true, 4); 11 p(semaphore, true, 5); 12 13 System.out.println("end"); 14 } 15 16 /** 17 * 停车 18 * 19 * @param semaphore 信号对象 20 * @param enterInto 停车true/出库false 21 * @param theCarNum 车辆序号 22 */ 23 private static void p(Semaphore semaphore, boolean enterInto, int theCarNum) { 24 if (!enterInto) { 25 try { 26 Thread.sleep(2000); 27 } catch (Exception e) { 28 e.printStackTrace(); 29 } 30 System.out.println("车辆出库"); 31 32 // 释放1个车位 33 // 通过LockSupport.unpark(s.thread)来释放锁,详见AbstractOwnableSynchronizer.unparkSuccessor 34 semaphore.release(1); 35 } 36 try { 37 // 如果达到设定的信号量,通过LockSupport.park(this)来释放锁,详见AbstractOwnableSynchronizer.parkAndCheckInterrupt 38 semaphore.acquire(); 39 System.out.println("第 " + theCarNum + " 辆车进入"); 40 } catch (Exception e) { 41 e.printStackTrace(); 42 } 43 44 } 45 46 /** 47 * Semaphore中Sync继承了AbstractQueuedSynchronizer 48 * 改变AbstractOwnableSynchronizer中state值(该值记录着剩余信号量) 49 * 50 * AbstractOwnableSynchronizer加载时会调用静态代码块获取state的偏移地址: 51 * stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state")); 52 * 上述获取对象某个变量的效率比使用反射获取的效率高 53 * 54 * protected final boolean compareAndSetState(int expect, int update) { 55 * // stateOffset为state变量的偏移地址 56 * return unsafe.compareAndSwapInt(this, stateOffset, expect, update); 57 * } 58 */ 59 60}
原文:https://blog.csdn.net/qq\_35001776/article/details/89158734