溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何實現(xiàn)Java線程安全的計數(shù)器

發(fā)布時間:2021-07-13 16:16:39 來源:億速云 閱讀:176 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)如何實現(xiàn)Java線程安全的計數(shù)器,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

前幾天工作中一段業(yè)務(wù)代碼需要一個變量每天從1開始遞增。為此自己簡單的封裝了一個線程安全的計數(shù)器,可以讓一個變量每天從1開始遞增。當(dāng)然了,如果項目在運(yùn)行中發(fā)生重啟,即便日期還是當(dāng)天,還是會從1開始重新計數(shù)。所以把計數(shù)器的值存儲在數(shù)據(jù)庫中會更靠譜,不過這不影響這段代碼的價值,現(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.
 * 一個循環(huán)計數(shù)器,每天從1開始計數(shù),隔天重置為1。
 * 可以創(chuàng)建一個該類的全局對象,然后每次使用時候調(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" 是為了測試addAndGet()方法中日期發(fā)生變化的情況
     * 正常使用應(yīng)該將key初始化為getCurrentDateString()
     */
    this.key = getCurrentDateString() + "sssssssssss";
    this.value = new AtomicInteger(0);
  }
  /**
   * 獲取計數(shù)器加1以后的值
   *
   * @return
   */
  public Integer addAndGet() {
    AtomicInteger oldValue = value;
    AtomicInteger newInteger = new AtomicInteger(0);
    int newVal = -1;
    String newDateStr = getCurrentDateString();
    //日期一致,計數(shù)器加1后返回
    if (isDateEquals(newDateStr)) {
      newVal = add(1);
      return newVal;
    }
    //日期不一致,保證有一個線程重置技術(shù)器
    reSet(oldValue, newInteger, newDateStr);
    this.key = newDateStr;
    //重置后加1返回
    newVal = add(1);
    return newVal;
  }
  /**
   * 獲取計數(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ā)生變化,重置計數(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;
  }
  /**
   * 計數(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 latch2 = new CountDownLatch(1);
    CountDownLatch latch3 = new CountDownLatch(size);
    for (int i = 0; i < size; i++) {
      Thread t = new Thread(new CounterRunner(c, latch2, latch3, count), "thread-" + i);
      li.add(t);
      t.start();
    }
    System.out.println("start");
    latch2.countDown();
    try {
      latch3.await();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println(count.get());
    System.out.println(c.get());
    if(count.get() == c.get()) {
      System.out.println("該計數(shù)器是線程安全的?。。?quot;);
    }
  }
  public static void main(String... args) {
    for(int i = 0; i < 15; i++) {
      test();
    }
  }
}
/**
 * 測試使用的Runnable對象
 */
class CounterRunner implements Runnable {
  private CircularCounter counter;
  private CountDownLatch latch2;
  private CountDownLatch latch3;
  private AtomicInteger count;
  public CounterRunner(CircularCounter counter, CountDownLatch latch2, CountDownLatch latch3, AtomicInteger count) {
    this.latch2 = latch2;
    this.latch3 = latch3;
    this.counter = counter;
    this.count = count;
  }
  @Override
  public void run() {
    try {
      latch2.await();
      System.out.println("****************");
      for (int i = 0; i < 20; i++) {
        counter.addAndGet();
        count.addAndGet(1);
      }
      latch3.countDown();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
}

關(guān)于“如何實現(xiàn)Java線程安全的計數(shù)器”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,使各位可以學(xué)到更多知識,如果覺得文章不錯,請把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI