假设我有一个非常简单的id生成器类,可以同时使用我的多个线程。下面的代码是否正常工作 - 我的意思是它总会返回唯一的ID?
class Generator{
private int counter=0;
public int getId(){
return counter++;//the key point is here
}
}
答案 0 :(得分:8)
没有。它根本不是线程安全的,您需要synchronize
getId()
方法。
然而,最好使用AtomicInteger.incrementAndGet()
。
public class Generator {
private final static AtomicInteger counter = new AtomicInteger();
public static int getId() {
return counter.incrementAndGet();
}
}
答案 1 :(得分:0)
您需要将计数器设为static
变量。并将方法设为static synchronize
。
答案 2 :(得分:0)
class Generator{
private static int counter=0;
public static synchronized int getId(){
return counter++;
}
}