Discuss / Java / demo,换成long就会出现重复id

demo,换成long就会出现重复id

Topic source

Loading...

#1 Created at ... [Delete] [Delete and Lock User]
public class OptimisticLock {
    public static void main(String[] args) {
       GenerateId id=new GenerateId();
        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                System.out.println(id.getNextId());
            }).start();
        }
//        System.out.println(id.getNextId());
    }
}
class GenerateId{
   AtomicLong l=new AtomicLong(0);
    public long getNextId(){
        return  l.incrementAndGet();
    }
}

我测试还好呀。jdk1.8

package demo.thread;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
public class TestAtomic {
    private static final AtomicLong atomicInteger = new AtomicLong(0);
    public static void main(String[] args) {
        Set<Long> set = new HashSet<>();
        
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    long id = getId();
                    set.add(id);
                    System.out.println(id);
                }
            };
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(set.size() == 30 ? "不重复" : "重复");
    }
    public static long getId() {
        return atomicInteger.incrementAndGet();
    }
}

为了严谨,换成了线程安全的set。

package demo.thread;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicLong;
public class TestAtomic {
    private static final AtomicLong atomicInteger = new AtomicLong(0);
    public static void main(String[] args) {
        Set<Long> set = new CopyOnWriteArraySet<>();
        for (int i = 0; i < 30; i++) {
            Thread thread = new Thread() {
                @Override
                public void run() {
                    long id = getId();
                    set.add(id);
                    System.out.println(id);
                }
            };
            thread.start();
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(set.size() == 30 ? "不重复" : "重复");
    }
    public static long getId() {
        return atomicInteger.incrementAndGet();
    }
}

佐上楼兰

#4 Created at ... [Delete] [Delete and Lock User]

你这块写的啥玩意儿

            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

你这相当于看似多线程的单线程,每次for循环都等待当前新建线程执行结束再进入下一循环,多线程基础回炉重造吧


  • 1

Reply