Java線程安全的計(jì)數(shù)器簡(jiǎn)單實(shí)現(xiàn)代碼示例
前幾天工作中一段業(yè)務(wù)代碼需要一個(gè)變量每天從1開始遞增。為此自己簡(jiǎn)單的封裝了一個(gè)線程安全的計(jì)數(shù)器,可以讓一個(gè)變量每天從1開始遞增。當(dāng)然了,如果項(xiàng)目在運(yùn)行中發(fā)生重啟,即便日期還是當(dāng)天,還是會(huì)從1開始重新計(jì)數(shù)。所以把計(jì)數(shù)器的值存儲(chǔ)在數(shù)據(jù)庫中會(huì)更靠譜,不過這不影響這段代碼的價(jià)值,現(xiàn)在貼出來,供有需要的人參考。
package com.hikvision.cms.rvs.common.util; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; /** * Created by lihong10 on 2017/8/9. * 一個(gè)循環(huán)計(jì)數(shù)器,每天從1開始計(jì)數(shù),隔天重置為1。 * 可以創(chuàng)建一個(gè)該類的全局對(duì)象,然后每次使用時(shí)候調(diào)用其get方法即可,可以保證線程安全性 */ public class CircularCounter { private static final AtomicReferenceFieldUpdater<CircularCounter, AtomicInteger> valueUpdater = AtomicReferenceFieldUpdater.newUpdater(CircularCounter.class, AtomicInteger.class, "value"); //保證內(nèi)存可見性 private volatile String key; //保證內(nèi)存可見性 private volatile AtomicInteger value; private static final String DATE_PATTERN = "yyyy-MM-dd"; public CircularCounter() { /** * 這里將key設(shè)置為getCurrentDateString() + "sssssssssss" 是為了測(cè)試addAndGet()方法中日期發(fā)生變化的情況 * 正常使用應(yīng)該將key初始化為getCurrentDateString() */ this.key = getCurrentDateString() + "sssssssssss"; this.value = new AtomicInteger(0); } /** * 獲取計(jì)數(shù)器加1以后的值 * * @return */ public Integer addAndGet() { AtomicInteger oldValue = value; AtomicInteger newInteger = new AtomicInteger(0); int newVal = -1; String newDateStr = getCurrentDateString(); //日期一致,計(jì)數(shù)器加1后返回 if (isDateEquals(newDateStr)) { newVal = add(1); return newVal; } //日期不一致,保證有一個(gè)線程重置技術(shù)器 reSet(oldValue, newInteger, newDateStr); this.key = newDateStr; //重置后加1返回 newVal = add(1); return newVal; } /** * 獲取計(jì)數(shù)器的當(dāng)前值 * @return */ public Integer get() { return value.get(); } /** * 判斷當(dāng)前日期與老的日期(也即key成員變量記錄的值)是否一致 * * @return */ private boolean isDateEquals(String newDateStr) { String oldDateStr = key; if (!isBlank(oldDateStr) && oldDateStr.equals(newDateStr)) { return true; } return false; } /** * 如果日期發(fā)生變化,重置計(jì)數(shù)器,也即將key設(shè)置為當(dāng)前日期,并將value重置為0,重置后才能接著累加, */ private void reSet(AtomicInteger oldValue, AtomicInteger newValue, String newDateStr) { if(valueUpdater.compareAndSet(this, oldValue, newValue)) { System.out.println("線程" + Thread.currentThread().getName() + "發(fā)現(xiàn)日期發(fā)生變化"); } } /** * 獲取當(dāng)前日期字符串 * * @return */ private String getCurrentDateString() { Date date = new Date(); String newDateStr = new SimpleDateFormat(DATE_PATTERN).format(date); return newDateStr; } /** * 計(jì)數(shù)器的值加1。采用CAS保證線程安全性 * * @param increment */ private int add(int increment) { return value.addAndGet(increment); } public static boolean isBlank(CharSequence cs) { int strLen; if(cs != null && (strLen = cs.length()) != 0) { for(int i = 0; i < strLen; ++i) { if(!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } else { return true; } } public static void test() { CircularCounter c = new CircularCounter(); AtomicInteger count = new AtomicInteger(0); List<Thread> li = new ArrayList<Thread>(); int size = 10; CountDownLatch latch1 = new CountDownLatch(1); CountDownLatch latch2 = new CountDownLatch(size); for (int i = 0; i < size; i++) { Thread t = new Thread(new CounterRunner(c, latch1, latch2, count), "thread-" + i); li.add(t); t.start(); } System.out.println("start"); latch1.countDown(); try { latch2.await(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(count.get()); System.out.println(c.get()); if(count.get() == c.get()) { System.out.println("該計(jì)數(shù)器是線程安全的!!!"); } } public static void main(String... args) { for(int i = 0; i < 15; i++) { test(); } } } /** * 測(cè)試使用的Runnable對(duì)象 */ class CounterRunner implements Runnable { private CircularCounter counter; private CountDownLatch latch1; private CountDownLatch latch2; private AtomicInteger count; public CounterRunner(CircularCounter counter, CountDownLatch latch1, CountDownLatch latch2, AtomicInteger count) { this.latch1 = latch1; this.latch2 = latch2; this.counter = counter; this.count = count; } @Override public void run() { try { latch1.await(); System.out.println("****************"); for (int i = 0; i < 20; i++) { counter.addAndGet(); count.addAndGet(1); } latch2.countDown(); } catch (InterruptedException e) { e.printStackTrace(); } } }
總結(jié)
以上就是本文關(guān)于Java線程安全的計(jì)數(shù)器簡(jiǎn)單實(shí)現(xiàn)代碼示例的內(nèi)容,希望對(duì)大家有所幫助,感興趣的朋友可以參閱:Java線程安全基礎(chǔ)概念解析、詳解java各種集合的線程安全 、Java線程安全與非線程安全解析等。有什么問題可以隨時(shí)留言,歡迎大家一起交流討論。感謝朋友們對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
Springboot使用POI實(shí)現(xiàn)導(dǎo)出Excel文件示例
本篇文章主要介紹了Springboot使用POI實(shí)現(xiàn)導(dǎo)出Excel文件示例,非常具有實(shí)用價(jià)值,需要的朋友可以參考下。2017-02-02java實(shí)體類轉(zhuǎn)json時(shí)null值不要轉(zhuǎn)為"null"問題
這篇文章主要介紹了java實(shí)體類轉(zhuǎn)json時(shí)null值不要轉(zhuǎn)為“null”問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11Spring Boot實(shí)現(xiàn)動(dòng)態(tài)更新任務(wù)的方法
這篇文章主要介紹了Spring Boot實(shí)現(xiàn)動(dòng)態(tài)更新任務(wù)的方法,文中給出了詳細(xì)的示例代碼供大家參考學(xué)習(xí),對(duì)大家學(xué)習(xí)使用Spring Boot動(dòng)態(tài)更新任務(wù)具有一定的參考價(jià)值,需要的朋友們來一起看看吧。2017-04-04java使用Jdom實(shí)現(xiàn)xml文件寫入操作實(shí)例
這篇文章主要介紹了java使用Jdom實(shí)現(xiàn)xml文件寫入操作的方法,以完整實(shí)例形式分析了Jdom針對(duì)XML文件寫入操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-10-10一文學(xué)會(huì)如何在SpringBoot中使用線程池執(zhí)行定時(shí)任務(wù)
在開發(fā)現(xiàn)代應(yīng)用程序時(shí),定時(shí)任務(wù)是一項(xiàng)常見的需求,SpringBoot提供了一個(gè)強(qiáng)大的定時(shí)任務(wù)框架,可以輕松地執(zhí)行各種定時(shí)任務(wù),結(jié)合線程池的使用,可以更好地管理任務(wù)的執(zhí)行,提高系統(tǒng)的性能和穩(wěn)定性,本文將介紹如何在Spring Boot中使用線程池執(zhí)行定時(shí)任務(wù)2023-06-06SpringBoot集成Sharding-JDBC實(shí)現(xiàn)分庫分表方式
這篇文章主要介紹了SpringBoot集成Sharding-JDBC實(shí)現(xiàn)分庫分表方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07java string 轉(zhuǎn)date方法如何實(shí)現(xiàn)
在開發(fā)應(yīng)用中經(jīng)常會(huì)使用到j(luò)ava string 轉(zhuǎn)date這種不是很常見的做法,本文將以此問題提供詳細(xì)解決方案,需要了解的朋友可以參考下2012-11-11