1. 程式人生 > >Java 產生隨機數 詳解

Java 產生隨機數 詳解

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();