我有一个简单的代码,我想用唯一的 id 生成对象。这是代码片段
public class Test {
private static long counter = 0;
private long id;
private Test() {
// Don't worry about overflow
id = counter++;
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}
想知道 getTest 方法是否被多个线程调用,所有 TestObject 都会有唯一的 id 吗?
最佳答案
它不是线程安全的,因为两个线程可以同时执行 counter++,你可能会得到意想不到的结果。
您应该使用 AtomicInteger:
public class Test {
private static AtomicLong counter = new AtomicLong(0);
private long id;
private Test() {
// Don't worry about overflow
id = counter.incrementAndGet();
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}
关于java - 这段代码对于java中的唯一id来说是线程安全的吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28208592/