您好,登錄后才能下訂單哦!
這篇文章主要介紹JAVA并發工具常用設計的示例分析,文中介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們一定要看完!
前言
在學習JAVA并發工具時,分析JUC下的源碼,發現有三個利器:狀態、隊列、CAS。
狀態
一般是state屬性,如AQS源碼中的狀態,是整個工具的核心,一般操作的執行都要看當前狀態是什么,
由于狀態是多線程共享的,所以都是volatile修飾,保證線程直接內存可見。
/** * AbstractQueuedSynchronizer中的狀態 */ private volatile int state; /** * Status field, taking on only the values: * SIGNAL: The successor of this node is (or will soon be) * blocked (via park), so the current node must * unpark its successor when it releases or * cancels. To avoid races, acquire methods must * first indicate they need a signal, * then retry the atomic acquire, and then, * on failure, block. * CANCELLED: This node is cancelled due to timeout or interrupt. * Nodes never leave this state. In particular, * a thread with cancelled node never again blocks. * CONDITION: This node is currently on a condition queue. * It will not be used as a sync queue node * until transferred, at which time the status * will be set to 0. (Use of this value here has * nothing to do with the other uses of the * field, but simplifies mechanics.) * PROPAGATE: A releaseShared should be propagated to other * nodes. This is set (for head node only) in * doReleaseShared to ensure propagation * continues, even if other operations have * since intervened. * 0: None of the above * * The values are arranged numerically to simplify use. * Non-negative values mean that a node doesn't need to * signal. So, most code doesn't need to check for particular * values, just for sign. * * The field is initialized to 0 for normal sync nodes, and * CONDITION for condition nodes. It is modified using CAS * (or when possible, unconditional volatile writes). */ volatile int waitStatus;
隊列
隊列一般由鏈表實現(單向鏈表,雙向鏈表),在線程獲取不到想要的資源或者狀態時,將線程封裝成特定節點,扔到等待隊列中,等待時機成熟,再從隊列中取出,是悲觀鎖思想。
如AQS中的Node節點,代碼太長就不貼了。
CAS
CAS操作是樂觀鎖思想,是輕量級的并發處理。一般用于對上述狀態的修改,而且能保證有且只有一個線程能修改這個狀態。
一般由Unsafe類中的compareAndSwap之類的方法實現。使用CAS,往往伴隨自旋,如果修改狀態失敗,則不斷地重試,直到修改狀態成功。
以上是“JAVA并發工具常用設計的示例分析”這篇文章的所有內容,感謝各位的閱讀!希望分享的內容對大家有幫助,更多相關知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。