在java中生成唯一ID的最佳方法

在java中生成唯一ID的最佳方法,java,uniqueidentifier,Java,Uniqueidentifier,在java中生成唯一ID的最佳方法是什么。人们通常使用 String id = System.currentTimeMillis+ someStaticCounter; 但这种方法需要在多线程应用程序中进行同步 我正在使用 try { Thread.sleep(1); //This sleep ensures that two consecutive calls from the same thread does not return the same id. } catch (

在java中生成唯一ID的最佳方法是什么。人们通常使用

String id = System.currentTimeMillis+ someStaticCounter;
但这种方法需要在多线程应用程序中进行同步

我正在使用

try 
{
   Thread.sleep(1); 
  //This sleep ensures that two consecutive calls from the same thread does not return the same id.
}
catch (InterruptedException e)
{
 // do nothing;
}
id = System.currentTimeMillis() + "-" + Thread.currentThread().getId();
这种方法可以帮助我避免同步开销

有没有更好的方法请推荐?

UUID如何:

UUID.randomUUID()

您是否需要此ID在多个虚拟机之间是唯一的?旁注:线程等待1ms不会防止使用相同的CurrentTimeMilli。如果两个线程开始在同一个ms(x)上睡眠,结束在同一个ms(x+1)上睡眠,则它们的并发可能性与睡眠前相同。此睡眠是为了防止同一线程生成相同的id。如果有两个不同的线程--thread.currentThread().getId()将确保两个线程的id不同,即使两个线程的currentTimeMillis()相同。