💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
如果只需要一个变量进行自增、自减操作,可以使用原子类,它们可以保证线程安全。这些类在`java.util.concurrent.atomic`包中。 <br/> 下面以 AtomicLong 类为例讲解。 <br/> **1. AtomicLong类** ``` public class AtomicLongTest { public static void main(String[] args) throws InterruptedException { AtomicLong atomicLong = new AtomicLong(); //id=0 System.out.println("id=" + atomicLong.get()); for (int i = 1; i <= 5; i++) { //每调用一次就增1 long id = atomicLong.incrementAndGet(); System.out.print(id + " "); //1 2 3 4 5 } //id=5 System.out.println("\nid=" + atomicLong.get()); for (int i = 1; i <= 5; i++) { //每调用一次就减1 long id = atomicLong.decrementAndGet(); //4 3 2 1 0 System.out.print(id + " "); } } } ``` **2. LongAdder | LongAccumulator类** 如果太多的线程访问同一个原子值,则`AtomicLong`类性能会大大下降,这种情况可以使用LongAdder,或LongAccumulator类代替。 ``` public class LongAdderTest { public static void main(String[] args) throws InterruptedException { LongAdder longAdder = new LongAdder(); //id=0 System.out.println("id=" + longAdder.sum()); for (int i = 1; i <= 5; i++) { //每调用一次就增1 longAdder.increment(); System.out.print(longAdder.sum() + " "); //1 2 3 4 5 } //id=5 System.out.println("\nid=" + longAdder.sum()); for (int i = 1; i <= 5; i++) { //每调用一次就减1 longAdder.decrement(); //4 3 2 1 0 System.out.print(longAdder.sum() + " "); } } } ```