使用ConcurrentHashMap保证线程安全性,唯一性,AtomicInteger实现自增长

本文介绍了如何在Java中利用ConcurrentHashMap保证线程安全性和唯一性,以及使用AtomicInteger实现17位代码的自增长。这17位代码由3位固定字符、9位当前时间戳和5位自增数构成,作为Uuid的替代方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

情景:需要生成17位代码来代替UUid,前3位固定,后五位使用 AtomicInteger实现自增长,中间9为是截取当前时间的年月日时分秒

自定义的DateUtil工具类:


```java


import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by babata on 2014/12/25.
 */
@Slf4j
public class DateUtil {
    public static final String timeFormate = "yyyy-MM-dd HH:mm:ss";
    public static final String dateFormate = "yyyy-MM-dd";
    public static final String pannelTime = "yyyyMMddHHmmss";
    public static final String yyyyMMdd = "yyyyMMdd";
    public static final String HHMMSS = "HH:mm:ss";
    /**
     * 获取系统时间 年月日时分秒
     * @return
     */
    public static String nowDateTime(){
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormate);
        Date date = new Date();
        return sdf.format(date);
    }

    public static String nowDay(){
        SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMdd);
        Date date = new Date();
        return sdf.format(date);
    }



    public static long getDistaceLong(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(timeFormate);
            Date date = sdf.parse(dateStr);
            return new Date().getTime() - date.getTime();
        }catch (Exception e){
            log.error("getDistaceLong error", e);
        }

        return 0;
    }

    public static String nowPannelDateTime(){
        SimpleDateFormat sdf = new SimpleDateFormat(pannelTime);
        Date date = new Date();
        return sdf.format(date);
    }


    public static Long nowDateTimeLong() {
        return new Date().getTime() ;
    }
    public static long time2Long(String time) {
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormate);
        Date date = null;
        try {
            date = sdf.parse(time);
        } catch (ParseException e) {
            log.error("exe error", e);
        }
        return date.getTime();
    }

    /**
     * 年月日
     * @return
     */
    public static String yyyyMMdd(){
        SimpleDateFormat sdf = new SimpleDateFormat(yyyyMMdd);
        Date date = new Date();
        return sdf.format(date);
    }

    public static String nowDateTimeSimple(){
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormate);
        Date date = new Date();
        return sdf.format(date);
    }

    public static String getNowHour(){
        SimpleDateFormat sdf = new SimpleDateFormat("HH");
        Date date = new Date();
        return sdf.format(date);
    }

    public static String getNowYear(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        Date date = new Date();
        return sdf.format(date);
    }
    public static String getNowMonth(){
        SimpleDateFormat sdf = new SimpleDateFormat("MM");
        Date date = new Date();
        return sdf.format(date);
    }
    public static String getNowDD(){
        SimpleDateFormat sdf = new SimpleDateFormat("dd");
        Date date = new Date();
        return sdf.format(date);
    }

    public static int[] getWeekNum(String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormate);
        Calendar cl = Calendar.getInstance();
        cl.setTime(sdf.parse(time));
        int week = cl.get(Calendar.WEEK_OF_YEAR);
        int year = cl.get(Calendar.YEAR);
        if(week<cl.get(Calendar.WEEK_OF_YEAR)){
            year+=1;
        }

        return new int[]{year,week};
    }

    public static Date parse2Date (String time,String fomate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(fomate);
        Date date = sdf.parse(time);
        return date;
    }

    public static String date2Str (Date date,String fomate) {
        SimpleDateFormat sdf = new SimpleDateFormat(fomate);
        return sdf.format(date);
    }

    public static Date parse2Date (String time) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormate);
        Date date = sdf.parse(time);
        return date;
    }


    public static String date2Str(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat(timeFormate);
        return sdf.format(date);
    }



    public static String date2Str (long date,String fomate) {
        SimpleDateFormat sdf = new SimpleDateFormat(fomate);
        return sdf.format(date);
    }

    public static String date2Str(Long ms) {
        Integer ss = 1000;
        Integer mi = ss * 60;
        Integer hh = mi * 60;
        Integer dd = hh * 24;

        Long day = ms / dd;
        Long hour = (ms - day * dd) / hh;
        Long minute = (ms - day * dd - hour * hh) / mi;
        Long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        Long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        StringBuffer sb = new StringBuffer();
        if(day > 0) {
            sb.append(day+"天");
        }

        if(hour > 0) {
            sb.append(hour+"小时");
        }
        if(minute > 0) {
            sb.append(minute+"分");
        }
        if(second > 0) {
            sb.append(second+"秒");
        }


//        if(milliSecond > 0) {
//            sb.append(milliSecond+"毫秒");
//        }
        return  String.valueOf(day * 24 + hour);
    }

    public static String oneHourAgo(){
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) - 1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());

    }
    public static String oneMonthAgo(){
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return df.format(calendar.getTime());

    }

    public static String getLastWeekStart(){
        Calendar date=Calendar.getInstance();
        date.setFirstDayOfWeek(Calendar.SUNDAY);//将每周第一天设为星期一,默认是星期天
        date.add(Calendar.WEEK_OF_MONTH,-1);//周数减一,即上周
        date.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);//日子设为星期天
        return date2Str(date.getTime(),dateFormate) + " 00:00:00";
    }

    public static String getLastWeekEnd(){
        Calendar date=Calendar.getInstance();
        date.setFirstDayOfWeek(Calendar.SUNDAY);//将每周第一天设为星期一,默认是星期天
        date.add(Calendar.WEEK_OF_MONTH,-1);//周数减一,即上周
        date.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);//日子设为星期天
        return date2Str(date.getTime(),dateFormate) + " 23:59:59";
    }


    public static void main(String[] args) {
        System.out.printf(oneMonthAgo());
    }




}

具体代码实现:

package com.sdqj.system_integration.utils;

import org.springframework.stereotype.Component;


import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class DeviceCodeGenrateUtil{
//固定字符串头部
    private static final String HUNAN_PREFIX = "16M";
//使用ConcurrentHashMap保证线程安全性,唯一性,AtomicInteger实现自增长
    public static ConcurrentHashMap<String, AtomicInteger> deviceCodeMap = new ConcurrentHashMap<String, AtomicInteger>();

    public synchronized   String CreateDeviceCode() {
//规定日期格式,
        String date = DateUtil.date2Str(new Date(),DateUtil.pannelTime);
        //截取其2-11位
        date = date.substring(2, 11);
        //将固定头和截取的日期拼接起来
        String codeKey = HUNAN_PREFIX + date;

        AtomicInteger intNextCrtID = deviceCodeMap.get(codeKey);
        if(intNextCrtID == null) {
            intNextCrtID  = new AtomicInteger(1);
            deviceCodeMap.put(codeKey, new AtomicInteger());
        }
        //自增
        int index = intNextCrtID.getAndIncrement();
        String indexStr = "00000".substring(0, 5-(index + "").length()) + index;

        //拼接17位字符串
        return codeKey + indexStr;
    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值