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