MK 發問時間: 電腦與網際網路程式設計 · 1 0 年前

JAVA亂數

請問JAVA的亂數

Math.random();

Random類別的 nextDouble();

兩個有什麼不一樣嗎?

1 個解答

評分
  • 1 0 年前
    最佳解答

    你可以看看Javadoc中Math.random()的說明:

    When this method is first called, it creates a single new pseudorandom-number generator, exactly as if by the expression

    new java.util.Random

    This new pseudorandom-number generator is used thereafter for all calls to this method and is used nowhere else.

    ^

    當Math.random()第一次被呼叫時,就會產生一個java.util.Random的實體,並在其後的呼叫都使用該實體來產生亂數。

    Math.random()其實是去呼叫 Random類別的nextDouble(),因此是一模一樣的。

    只差在Math.random( )有同步化,Random.nextDouble()沒有,要自己處理多執行緒同步的問題,如Javadoc中提到的:

    This method is properly synchronized to allow correct use by more than one thread. However, if many threads need to generate pseudorandom numbers at a great rate, it may reduce contention for each thread to have its own pseudorandom-number generator.

還有問題?馬上發問,尋求解答。