隨機數生成器只產生一個隨機數的問題及解決方案
本文討論一個隨機數生成器函數RandomNumber
只產生一個隨機數的問題。問題根源在於該函數每次調用時都創建一個新的Random
實例。由於Random
實例的內部狀態基於系統時鐘初始化,在緊密的循環中,多次調用會得到相同的值。
為了解決這個問題並確保隨機數的準確性,應該創建一個Random
實例並重複使用。以下代碼展示瞭如何實現:
<code class="language-csharp">private static readonly Random random = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { return random.Next(min, max); } }</code>
通過使用lock
語句,我們同步對Random
實例的訪問,保證同一線程內每次調用RandomNumber
都會產生一個唯一的隨機數。
另一種方法是使用ThreadLocal
變量為每個線程維護一個Random
實例,從而避免同步:
<code class="language-csharp">private static readonly ThreadLocal<Random> appRandom = new ThreadLocal<Random>(() => new Random());</code>
以上是為什麼我的隨機數生成器只會產生一個數字,我該如何修復?的詳細內容。更多資訊請關注PHP中文網其他相關文章!