Java 產生隨機數 詳解__Java

來源:互聯網
上載者:User
Math.random() 方法可以隨機產生一個 [0, 1) 直接的數,包括 0,不包括 1
產生 0 到 10 之間的整數 # 使用 Math.round(Math.random() * 10)) ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) {     executorService.submit(() -> System.out.println(Math.round(Math.random() * 10))); } executorService.shutdown();
也可以使用 new java.util.Random().nextInt(11) 方式產生 0 到 10 之間的整數,java.util.Random是安全執行緒的,所以不存在多個線程調用會破壞種子(seed)的風險,但是使用 Random 類需要建立執行個體 ExecutorService executorService = Executors.newFixedThreadPool(10); for (int i = 0; i < 100; i++) {     executorService.submit(() -> System.out.println(new Random().nextInt(11))); } executorService.shutdown();
Java 7 中提供一個 單一執行個體/靜態訪問 的隨機類 java.util.concurrent.ThreadLocalRandom,和 Math.random()一樣靈活且比其他任何處理高並發的方法要更快 `java.util.concurrent.ThreadLocalRandom.current().nextInt(11) // 線程隔離的產生隨機數 ExecutorService executorService = Executors.newFixedThreadPool(11); for (int i = 0; i < 100; i++) {     executorService.submit(() -> System.out.println(Thread.currentThread().getName() + " : " + ThreadLocalRandom.current().nextInt(10))); } executorService.shutdown();

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.