生成訂單號

package com.jszc.lottery.common.utils;

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

/**
 * 
 * 訂單號生成工具,生成非重複訂單號,理論上限1毫秒1000個,可擴展
 *
 */
public class MakeOrderNumUtil {
    /**
     * 鎖對象,可以爲任意對象
     */
    private static Object lockObj = "lockerOrder";
    /**
     * 訂單號生成計數器
     */
    private static long orderNumCount = 0L;
    /**
     * 每毫秒生成訂單號數量最大值
     */
    private int maxPerMSECSize = 1000;

    /**
     * 生成非重複訂單號,理論上限1毫秒1000個
     */
    public String makeOrderNum() {
        // 最終生成的訂單號
        String finOrderNum = "";
        synchronized (lockObj) {
            // 取系統當前時間作爲訂單號變量前半部分,精確到毫秒
            String nowDate = new SimpleDateFormat("HHmmssSSS").format(new Date());
            // 計數器到最大值歸零,可擴展更大,目前1毫秒處理峯值1000個,1秒100萬
            if (orderNumCount > maxPerMSECSize) {
                orderNumCount = 0L;
            }
            // 組裝訂單號
            String countStr = maxPerMSECSize + orderNumCount + "";
            finOrderNum = nowDate + countStr.substring(1);
            orderNumCount++;
        }
        return finOrderNum;
    }

    public static void main(String[] args) {
        // 測試多線程調用訂單號生成工具
        try {
            for (int i = 0; i < 200; i++) {
                Thread t1 = new Thread(new Runnable() {
                    public void run() {
                        MakeOrderNumUtil makeOrder = new MakeOrderNumUtil();
                        String finOrderNum = makeOrder.makeOrderNum();
                        System.out.println(finOrderNum+"zss");
                    }
                }, "at" + i);
                t1.start();
                Thread t2 = new Thread(new Runnable() {
                    public void run() {
                        MakeOrderNumUtil makeOrder = new MakeOrderNumUtil();
                        String finOrderNum = makeOrder.makeOrderNum();
                        System.out.println(finOrderNum+"zss" );
                    }
                }, "bt" + i);
                t2.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章