public class MyThreadTest {private final static Semaphore semaphore = new Semaphore(2);// 設置2個車位public static void main(String[] args) {System.out.println("start");p(semaphore, true, 1);p(semaphore, false, 2);p(semaphore, false, 3);p(semaphore, true, 4);p(semaphore, true, 5);System.out.println("end");}/*** 停車** @param semaphore 信號對象* @param enterInto 停車true/出庫false* @param theCarNum 車輛序號*/private static void p(Semaphore semaphore, boolean enterInto, int theCarNum) {if (!enterInto) {try {Thread.sleep(2000);} catch (Exception e) {e.printStackTrace();}System.out.println("車輛出庫");// 釋放1個車位// 通過LockSupport.unpark(s.thread)來釋放鎖,詳見AbstractOwnableSynchronizer.unparkSuccessorsemaphore.release(1);}try {// 如果達到設定的信號量,通過LockSupport.park(this)來釋放鎖,詳見AbstractOwnableSynchronizer.parkAndCheckInterruptsemaphore.acquire();System.out.println("第 " + theCarNum + " 輛車進入");} catch (Exception e) {e.printStackTrace();}}/*** Semaphore中Sync繼承了AbstractQueuedSynchronizer* 改變AbstractOwnableSynchronizer中state值(該值記錄著剩余信號量)** AbstractOwnableSynchronizer加載時會調用靜態代碼塊獲取state的偏移地址:* stateOffset = unsafe.objectFieldOffset(AbstractQueuedSynchronizer.class.getDeclaredField("state"));* 上述獲取對象某個變量的效率比使用反射獲取的效率高** protected final boolean compareAndSetState(int expect, int update) {* // stateOffset為state變量的偏移地址* return unsafe.compareAndSwapInt(this, stateOffset, expect, update);* }*/}
原文:https://blog.csdn.net/qq_35001776/article/details/89158734