• Random是线程安全的
  • ThreadLocalRandom在高并发场景下建议使用

    Random实现短信验证码

    ```java
  1. public static void main(String[] args) {
  2. System.out.println(verificationCode(8));
  3. System.out.println(randomPassword(8));
  4. }
  5. /**
  6. * 生产随机验证码
  7. */
  8. public static String verificationCode(int length) {
  9. if (4 != length & 6 != length & 8 != length) {
  10. throw new RuntimeException("错误");
  11. }
  12. char[] chars = new char[length];
  13. Random random = new Random();
  14. for (int i = 0; i < length; i++) {
  15. chars[i] = (char) ('0' + random.nextInt(10));
  16. }
  17. return new String(chars);
  18. }
  19. private static final String SPECIAL_CHARS = "!@#$%^&*/|";
  20. /**
  21. * 生产随机字符
  22. * @param random
  23. * @return
  24. */
  25. public static char nextChar(Random random){
  26. switch (random.nextInt(4)){
  27. case 0 :
  28. return (char) ('0' + random.nextInt(10));
  29. case 1 :
  30. return (char) ('A' + random.nextInt(26));
  31. case 2 :
  32. return (char) ('a' + random.nextInt(26));
  33. default: return SPECIAL_CHARS.charAt(random.nextInt(SPECIAL_CHARS.length()));
  34. }
  35. }
  36. /**
  37. * 生产随机密码
  38. * 密码长度最好12位
  39. * @param length
  40. * @return
  41. */
  42. public static String randomPassword(int length){
  43. if (6 > length){
  44. throw new RuntimeException("密码长度必须为六位以上");
  45. }
  46. char[] chars = new char[length];
  47. ThreadLocalRandom random = ThreadLocalRandom.current();
  48. for (int i = 0; i < length; i++) {
  49. chars[i] = nextChar(random);
  50. }
  51. return new String(chars);
  52. }

```

ThreadLocalRandom实现随机密码