[英]Java: thread safe id generator (synchronization issue)
假设我有一个非常简单的id生成器类,可以同时使用我的多个线程。 以下代码是否正常工作 - 我的意思是它总会返回唯一的ID?
class Generator{
private int counter=0;
public int getId(){
return counter++;//the key point is here
}
}
不。它根本不是线程安全的,你需要synchronize
你的getId()
方法。
但是最好使用AtomicInteger.incrementAndGet()
代替。
public class Generator {
private final static AtomicInteger counter = new AtomicInteger();
public static int getId() {
return counter.incrementAndGet();
}
}
您需要将计数器作为static
变量。 并将方法作为static synchronize
。
class Generator{
private static int counter=0;
public static synchronized int getId(){
return counter++;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.