繁体   English   中英

Java:线程安全id生成器(同步问题)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM