日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > java >内容正文

java

Java并发Semaphore信号量的学习

發布時間:2023/11/30 java 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java并发Semaphore信号量的学习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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

轉載于:https://www.cnblogs.com/qbdj/p/10869946.html

總結

以上是生活随笔為你收集整理的Java并发Semaphore信号量的学习的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。