Discuss / 编程 / 如何验证唯一性

如何验证唯一性

Topic source

还是有重复的id生成,不知道这样验证是否正确呢

public class IdUtilTest {
    public static void main(String[] args) throws InterruptedException {
        Set<Long> idSet = Sets.newHashSet();        
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                idSet.add(IdUtil.nextId());            
            }
        });        
        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 50000; i++) {
                idSet.add(IdUtil.nextId());            
            }
        });        
        t1.start();        
        t2.start();        
        t1.join();        
        t2.join();        
        System.out.println("生成id完毕");        
        System.out.println(idSet.size());    
    }
}

最后我输出的结果是不足10万

这是因为hastset不是线程安全的吧

Yanlun0323

#3 Created at ... [Delete] [Delete and Lock User]
Sets.newConcurrentHashSet();

按照你的多线程思路,因为HashSet本身线程不安全,可将Sets.newHashSet()改成Sets.newConcurrentHashSet();得到的结果是10W。


  • 1

Reply