import java.util.Random;
public class RandomString {
/**
* 产生随机字符串
* */
private static Random random = null;
private static char[] numbersAndLetters = null;
private static Object initLock = new Object();
/**
* @param args
*/
public static void main(String[] args) {
String str=randomString(6);
System.out.println(str);
}
public static String randomString(int length) {
if (length < 1) {
return null;
}
if (random == null) {
//同步锁定
synchronized (initLock) {
if (random == null) {
random = new Random();
numbersAndLetters = ("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
}
}
}
char [] randBuffer = new char[length];
for (int i=0; i<randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[random.nextInt(35)];
}
return new String(randBuffer);
}
}
产生随机字符串
最新推荐文章于 2024-07-24 10:08:20 发布