在java中生成唯一ID的最佳方法 [英] Best way to generate a unique ID in java

查看:399
本文介绍了在java中生成唯一ID的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

What is the best way to generate a unique ID in java. People generally use

String id = System.currentTimeMillis+ someStaticCounter;

但这种方法需要在多线程应用程序中进行同步。

But this approach would require synchronization in multithreaded applications.

我正在使用

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

这种方法可以帮助我避免同步开销..

This approach helps me from synchronisation overheads..

有什么更好的方法请建议吗?

Is there any better approach please suggest?

推荐答案

UUID怎么样:
http://java.sun.com/j2se /1.5.0/docs/api/java/util/UUID.html#randomUUID%28%29

这篇关于在java中生成唯一ID的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆