Java 產生 不重複的 隨機數
package com.cloud.sea.random;import java.util.Arrays;import java.util.Random;/** * 產生不重複的隨機數 * * @author Henry Lee * @version 1.0 */public class GenNotRepeatRandom {public static void main(String[] args) throws TargetMinException {int[] arr = GenNotRepeatRandom.genNum(30, 30);GenNotRepeatRandom.showArr(arr, false);}/** * 產生不重複隨機數 * * @param num * 隨機數個數 * @param value * 隨機數範圍 * @see 注意value不可小於num * @return * @throws TargetMinException */public static int[] genNum(int num, int value) throws TargetMinException {int[] arr = new int[num];// 儲存最終產生結果int index = 0;// 狀態索引 default = 0arr = new int[num];if (value < num) {throw new TargetMinException("隨機數取值範圍不可以小於產生隨機數個數");}boolean result = true;while (result) {// 控制是否繼續產生隨機數Random rd = new Random();int tempRandomNum = rd.nextInt(value) + 1;if (arr[arr.length - 1] == 0) {// 決定是否繼續產生隨機數進行賦值if (isHas(tempRandomNum, arr, index)) {// 判斷已產生隨機數是否與數組中已有數值重複continue;}arr[index++] = tempRandomNum;// 將產生的不重複發的隨機數放入數組中} elseresult = false;}return arr;}/** * 判斷是否已存在產生的隨機數 * * @param mm * @param arr * @param index * @return */private static boolean isHas(int tempRandomNum, int[] arr, int index) {for (int i = 0; i < index; i++) {if (tempRandomNum == arr[i]) {return true;}}return false;}/** * showArr * * @param arr * @param isSort */@Deprecatedpublic static void showArr(int[] arr, boolean isSort) {for (int j = 0; j < arr.length; j++) {if (isSort) {Arrays.sort(arr);}System.out.print(arr[j] + ",");}}static class TargetMinException extends Exception {private static final long serialVersionUID = 1L;public String message = "";public TargetMinException(String message) {this.message = message;}@Overridepublic String getMessage() {return this.message;}}}
線程調用
package com.cloud.sea.random;import java.util.HashMap;import java.util.Map;import com.cloud.sea.random.GenNotRepeatRandom.TargetMinException;/** * 線程調用 * @author Henry Lee * */public class ThreadImp1 implements Runnable{String key = null;/** * 靜態變數map儲存結果 * 其他類擷取對應線程執行結果 */public static Map<String,int[]> map = new HashMap<String, int[]>();public ThreadImp1(String key){this.key = key;}public void run() {int[] arr = null;try {arr = GenNotRepeatRandom.genNum(1500, 30000);} catch (TargetMinException e) {e.printStackTrace();}map.put(key, arr);}}
package com.cloud.sea.random;public class ThreadTest {public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 100; i++) {ThreadImp1 timp = new ThreadImp1(i + "");Thread t = new Thread(timp);t.start();}Thread.sleep(3000);for (int i = 0; i < 100; i++) {int[] arr = ThreadImp1.map.get(i + "");for (int j = 0; j < arr.length; j++) {System.out.print(arr[j] + ",");}System.out.println();}}}