Java并发AtomicInteger类

Java并发AtomicInteger类


java.util.concurrent.atomic.AtomicInteger类提供对基本int值的操作,该值可以以原子方式读取和写入,并且还包含高级的原子操作。AtomicInteger支持底层int变量的原子操作。它具有读取和写入易失性变量的方法。也就是说,一个集合与之后的任何一个变量之间都有一个前后关系。原子compareAndSet方法也具有这些内存一致性功能。

AtomicInteger方法

以下是AtomicInteger类中可用的重要方法的列表。

Sr.No.方法和描述
1public int addAndGet(int delta) 原子上将给定值添加到当前值。
2public boolean compareAndSet(int expect,int update) 如果当前值与期望值相同,则按原子值将该值设置为给定的更新值。
3public int decrementAndGet() 原子减少一个当前值。
4public double doubleValue() 以double形式返回指定数字的值。
5public float floatValue() 以浮点形式返回指定数字的值。
6public int get() 获取当前值。
7public int getAndAdd(int delta) Atomiclly将给定值添加到当前值。
8public int getAndDecrement() 原子减少一个当前值。
9public int getAndIncrement() 原子上增加一个当前值。
10public int getAndSet(int newValue) 原子级设置为给定值并返回旧值。
11public int incrementAndGet() 原子上增加一个当前值。
12public int intValue() 以int形式返回指定数字的值。
13public void lazySet(int newValue) 最终设置为给定值。
14public long longValue() 以长整数形式返回指定数字的值。
15public void set(int newValue) 设置为给定值。
16public String toString() 返回当前值的字符串表示形式。
17public boolean weakCompareAndSet(int expect,int update) 如果当前值与期望值相同,则按原子值将该值设置为给定的更新值。

以下TestThread程序显示基于线程的环境中不安全的计数器实现。

public class TestThread {

   static class Counter {
      private int c = 0;

      public void increment() {
         c++;
      }

      public int value() {
         return c;
      }
   }

   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();

      //1000 threads
      for(int i = 0; i < 1000 ; i++) {

         new Thread(new Runnable() {

            public void run() {
               counter.increment();
            }
         }).start();
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }  
}

根据计算机的速度和线程交错,这可能会产生以下结果。

输出

Final number (should be 1000): 1000

以下TestThread程序在基于线程的环境中使用AtomicInteger显示计数器的安全实现。

import java.util.concurrent.atomic.AtomicInteger;

public class TestThread {

   static class Counter {
      private AtomicInteger c = new AtomicInteger(0);

      public void increment() {
         c.getAndIncrement();
      }

      public int value() {
         return c.get();
      }
   }

   public static void main(final String[] arguments) throws InterruptedException {
      final Counter counter = new Counter();

      //1000 threads
      for(int i = 0; i < 1000 ; i++) {

         new Thread(new Runnable() {
            public void run() {
               counter.increment();
            }
         }).start();
      }  
      Thread.sleep(6000);
      System.out.println("Final number (should be 1000): " + counter.value());
   }
}

这将产生以下结果。

输出

Final number (should be 1000): 1000
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值