- Random是线程安全的
- ThreadLocalRandom在高并发场景下建议使用
Random实现短信验证码
```java
public static void main(String[] args) {
System.out.println(verificationCode(8));
System.out.println(randomPassword(8));
}
/**
* 生产随机验证码
*/
public static String verificationCode(int length) {
if (4 != length & 6 != length & 8 != length) {
throw new RuntimeException("错误");
}
char[] chars = new char[length];
Random random = new Random();
for (int i = 0; i < length; i++) {
chars[i] = (char) ('0' + random.nextInt(10));
}
return new String(chars);
}
private static final String SPECIAL_CHARS = "!@#$%^&*/|";
/**
* 生产随机字符
* @param random
* @return
*/
public static char nextChar(Random random){
switch (random.nextInt(4)){
case 0 :
return (char) ('0' + random.nextInt(10));
case 1 :
return (char) ('A' + random.nextInt(26));
case 2 :
return (char) ('a' + random.nextInt(26));
default: return SPECIAL_CHARS.charAt(random.nextInt(SPECIAL_CHARS.length()));
}
}
/**
* 生产随机密码
* 密码长度最好12位
* @param length
* @return
*/
public static String randomPassword(int length){
if (6 > length){
throw new RuntimeException("密码长度必须为六位以上");
}
char[] chars = new char[length];
ThreadLocalRandom random = ThreadLocalRandom.current();
for (int i = 0; i < length; i++) {
chars[i] = nextChar(random);
}
return new String(chars);
}
```
ThreadLocalRandom实现随机密码