日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

多线程1:AtomicInteger的使用,多线程叠加或叠减

發布時間:2024/1/23 编程问答 34 豆豆
生活随笔 收集整理的這篇文章主要介紹了 多线程1:AtomicInteger的使用,多线程叠加或叠减 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Java語言中,++i和i++操作并不是線程安全的,在使用的時候,不可避免的會用到synchronized關鍵字。而AtomicInteger則通過一種線程安全的加減操作接口 [java]?view plaincopy
  • import?java.util.concurrent.atomic.AtomicInteger;??
  • ??
  • public?class?AtomicIntegerTest?{??
  • ????public?AtomicInteger?inc?=?new?AtomicInteger();??
  • ??
  • ????public?void?increase()?{??
  • ????????inc.getAndIncrement();//i++操作??
  • ????????//inc.getAndDecrement();//i--操作??
  • ????}??
  • ??
  • ????public?static?void?main(String[]?args)?{??
  • ????????final?AtomicIntegerTest?test?=?new?AtomicIntegerTest();??
  • ????????for?(int?i?=?0;?i?<?10;?i++)?{??
  • ????????????new?Thread()?{??
  • ????????????????public?void?run()?{??
  • ????????????????????for?(int?j?=?0;?j?<?1000;?j++)??
  • ????????????????????????test.increase();??
  • ????????????????};??
  • ????????????}.start();??
  • ????????}??
  • ??
  • ????????while?(Thread.activeCount()?>?1)??
  • ????????????//?保證前面的線程都執行完??
  • ????????????Thread.yield();??
  • ????????System.out.println(test.inc);??
  • ????}??
  • }??

  •  可以發現結果都是10000,也就是說AtomicInteger是線程安全的。

    值得一看。

    這里,我們來看看AtomicInteger是如何使用非阻塞算法來實現并發控制的。

    AtomicInteger的關鍵域只有一下3個:

    [java]?view plaincopy
  • //?setup?to?use?Unsafe.compareAndSwapInt?for?updates????
  • private?static?final?Unsafe?unsafe?=?Unsafe.getUnsafe();????
  • private?static?final?long?valueOffset;????
  • private?volatile?int?value;????

  • 這里, unsafe是Java提供的獲得對對象內存地址訪問的類,注釋已經清楚的寫出了,它的作用就是在更新操作時提供“比較并替換”的作用。實際上就是AtomicInteger中的一個工具。

    valueOffset是用來記錄value本身在內存的便宜地址的,這個記錄,也主要是為了在更新操作在內存中找到value的位置,方便比較。

    注意:value是用來存儲整數的時間變量,這里被聲明為volatile,就是為了保證在更新操作時,當前線程可以拿到value最新的值(并發環境下,value可能已經被其他線程更新了)。

    這里,我們以自增的代碼為例,可以看到這個并發控制的核心算法:

    [java]?view plaincopy
  • /**?
  • *?Atomically?increments?by?one?the?current?value.?
  • *?
  • *?@return?the?updated?value?
  • */??
  • public?final?int?incrementAndGet()?{??
  • for?(;;)?{??
  • //這里可以拿到value的最新值??
  • int?current?=?get();??
  • int?next?=?current?+?1;??
  • if?(compareAndSet(current,?next))??
  • return?next;??
  • }??
  • }??
  • ??
  • public?final?boolean?compareAndSet(int?expect,?int?update)?{??
  • //使用unsafe的native方法,實現高效的硬件級別CAS??
  • return?unsafe.compareAndSwapInt(this,?valueOffset,?expect,?update);??
  • }??

  • ?好了,看到這個代碼,基本上就看到這個類的核心了。相對來說,其實這個類還是比較簡單的。可以參考http://hittyt.iteye.com/blog/1130990 創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎

    總結

    以上是生活随笔為你收集整理的多线程1:AtomicInteger的使用,多线程叠加或叠减的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。