本篇文章給大家?guī)淼膬?nèi)容是java如何實(shí)現(xiàn)線程安全的計數(shù)器?實(shí)現(xiàn)線程安全的計數(shù)器的方法。有一定的參考價值,有需要的朋友可以參考一下,希望對你們有所幫助。
線程安全的計數(shù)器實(shí)現(xiàn)原理簡介:
在java中volatile關(guān)鍵字可以保證共享數(shù)據(jù)的可見性,它會把更新后的數(shù)據(jù)從工作內(nèi)存刷新進(jìn)共享內(nèi)存,并使其他線程中工作內(nèi)存中的數(shù)據(jù)失效,進(jìn)而從主存中讀入最新值來保證共享數(shù)據(jù)的可見性,實(shí)現(xiàn)線程安全的計數(shù)器通過循環(huán)CAS操作來實(shí)現(xiàn)。就是先獲取一個舊期望值值,再比較獲取的值與主存中的值是否一致,一致的話就更新,不一致的話接著循環(huán),直到成功為止.
具體代碼實(shí)現(xiàn)
public class Count{ private int count = 0; private AtomicInteger atomicI = new AtomicInteger(0); public static void main(String[] args){ final Count cas = new Count(); List<Thread> list = new ArrayList<Thread>(); long start = System.currentTimeMillis(); for(int j=0;j<100;j++){ Thread t = new Thread(new Runnable(){ @Override public void run(){ for(int i=0;i<1000;i++){ cas.count(); cas.safeCount(); } } }); list.add(t); } //啟動線程 for(Thread t:list){ t.start(); } //等待所有線程執(zhí)行完畢 for(Thread t:list){ try{ t.join(); }catch(Exception e){ e.printStackTrace(); } } System.out.println("線程不安全:"+cas.count); System.out.println("線程安全:"+cas.atomicI.get()); System.out.println("耗時:"+(System.currentTimeMillis() - start)); } /**線程不安全的計數(shù)器*/ public void count(){ count++; } /**線程安全的計數(shù)器,循環(huán)CAS*/ public void safeCount(){ for(;;){ int temp = atomicI.get(); if(atomicI.compareAndSet(temp,++temp)) break; } } }
執(zhí)行結(jié)果:
以上就是java如何實(shí)現(xiàn)線程安全的計數(shù)器?實(shí)現(xiàn)線程安全的計數(shù)器的方法的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
java怎么學(xué)習(xí)?java怎么入門?java在哪學(xué)?java怎么學(xué)才快?不用擔(dān)心,這里為大家提供了java速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.miracleart.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號