IdGenerator.java UUID

package id;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.Random;

/**
 * UUID
 * 
 * @author ZengWenFeng
 * @date 2010.09.21
 */
public class IdGenerator
{
	// 使用ThreadLocal确保SimpleDateFormat的线程安全
	private static final ThreadLocal formatter = new ThreadLocal()
	{
		protected SimpleDateFormat initialValue()
		{
			return new SimpleDateFormat("yyyyMMddHHmm");
		}
	};

	// 生成线程安全的ID(全部大写)
	public static String generateId()
	{
		// 获取当前时间并格式化为字符串
		String timestamp = formatter.get().format(new Date());

		// 生成32位UUID(去掉连字符)并转为大写
		String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();

		// 组合时间戳和UUID
		return timestamp + "-" + uuid;
	}

	// 可选:使用随机数生成方式(JDK6兼容),全部大写
	public static String generateIdWithRandom()
	{
		String timestamp = formatter.get().format(new Date());

		// 使用Random生成32位十六进制随机数(大写)
		StringBuilder uuid = new StringBuilder(32);
		Random random = new Random();
		for (int i = 0; i < 32; i++)
		{
			uuid.append(Integer.toHexString(random.nextInt(16)).toUpperCase());
		}

		return timestamp + "-" + uuid.toString();
	}

	// 更线程安全的随机数生成方式(JDK6兼容)
	public static String generateIdWithThreadLocalRandom()
	{
		String timestamp = formatter.get().format(new Date());

		// 模拟ThreadLocalRandom(JDK6中没有ThreadLocalRandom)
		StringBuilder uuid = new StringBuilder(32);
		Random random = new Random(System.nanoTime());
		for (int i = 0; i < 32; i++)
		{
			uuid.append(Integer.toHexString(random.nextInt(16)).toUpperCase());
		}

		return timestamp + "-" + uuid.toString();
	}

	public static void main(String[] args)
	{
		// 测试生成ID
		System.out.println("Generated ID: " + generateId());
		System.out.println("Generated ID with random: " + generateIdWithRandom());
		System.out.println("Generated ID with thread-local random: " + generateIdWithThreadLocalRandom());
	}
}

你可能感兴趣的:(java,java,UUID)