`
wlh269
  • 浏览: 447196 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

产生随机字符串

    博客分类:
  • J2SE
阅读更多

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


}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics