首页 技术 正文
技术 2022年11月6日
0 收藏 509 点赞 968 浏览 1761 个字

Java 中无锁的线程安全整数 AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,

不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。AtomicInteger为什么能够达到多而不乱,处理高并发应付自如呢?

这是由硬件提供原子操作指令实现的,这里面用到了一种并发技术:CAS。在非激烈竞争的情况下,开销更小,速度更快。Java.util.concurrent中实现的原子操作类包括:AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、AtomicReferenceArray。

/**
 * 来看AtomicInteger提供的接口。

//获取当前的值
 
 public final int get()
 
 //取当前的值,并设置新的值
 
  public final int getAndSet(int newValue)
 
 //获取当前的值,并自增
 
  public final int getAndIncrement()
 
 //获取当前的值,并自减
 
 public final int getAndDecrement()
 
 //获取当前的值,并加上预期的值
 
 public final int getAndAdd(int delta)

例子代码为:

AtomicOperationDemo.java

  1. import java.util.*;
  2. import java.util.concurrent.*;
  3. import java.util.concurrent.atomic.*;
  4. /*
  5. * ava.util.concurrent中实现的原子操作类包括:
  6. AtomicBoolean、AtomicInteger、AtomicIntegerArray、AtomicLong、AtomicReference、
  7. AtomicReferenceArray。
  8. *
  9. */
  10. public class AtomicOperationDemo {
  11. static AtomicInteger count=new AtomicInteger(0);
  12. public static class AddThread implements Runnable{
  13. @Override
  14. public void run() {
  15. for(int k=0;k<1000;k++){
  16. count.incrementAndGet();
  17. }
  18. }
  19. }
  20. public static void AtomicIntShow(){
  21. System.out.println(“AtomicIntShow() enter”);
  22. ExecutorService threadpool =   Executors.newFixedThreadPool(10);
  23. for(int k=0;k<100;k++){
  24. threadpool.submit(new AddThread());
  25. }
  26. try {
  27. Thread.sleep(2000);
  28. } catch (InterruptedException e) {
  29. // TODO Auto-generated catch block
  30. e.printStackTrace();
  31. }
  32. /* output
  33. * AtomicIntShow() enter
  34. * result of acumulated sum=100000
  35. * AtomicIntShow() exit
  36. */
  37. System.out.println(“result of acumulated sum=”+count);
  38. threadpool.shutdown();
  39. System.out.println(“AtomicIntShow() exit”);
  40. return ;
  41. }
  42. }

Maintest.java

  1. public class Maintest {
  2. public static void main(String[] args) {
  3. AtomicOperationDemo.AtomicIntShow();
  4. }
  5. }
    1. /* output
    2. * result of acumulated sum=100000
    3. */
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,105
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,582
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,429
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,836
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,919