java并发⽣成商品编号
package ator;
import java.time.Instant;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import urrent.Callable;
import urrent.ExecutionException;
import urrent.FutureTask;
import urrent.ThreadLocalRandom;
import urrent.atomic.AtomicInteger;
import org.apachemons.lang3.time.FastDateFormat;
import org.springframework.util.StopWatch;
/**
* 订单编号策略
*
* @project common-utils
* @fileName ODDGenerator.java
* @Description
* @author light-zhang
* @date 2018年5⽉11⽇
* @version 1.0.0
*/
public abstract class ODDGenerator {
private static final FastDateFormat pattern = Instance("yyyyMMddHHmmss");
private static final AtomicInteger atomicInteger = new AtomicInteger(1);
private static ThreadLocal<StringBuilder> threadLocal = new ThreadLocal<StringBuilder>();
/**
* 长码⽣成策略
*  20201116114351753590384993
* @param lock uuid
* @return
*/
public static String getC(String lock) {
if (Objects.())) {
lock = Objects.isNull(lock) ? UUID.randomUUID().toString() : lock;
StringBuilder builder = new StringBuilder(pattern.w().toEpochMilli()));// 取系统当前时间作为订单号前半部分            builder.append(Math.abs(lock.hashCode()));// HASH-CODE
builder.AndIncrement());// ⾃增顺序
threadLocal.set(builder);
}
().toString();
java生成随机数的方法
}
/**
* 短码⽣成策略
* 1307891882965
* @param lock
* @return
*/
public static String getD(String lock) {
if (Objects.())) {
lock = Objects.isNull(lock) ? UUID.randomUUID().toString() : lock;
StringBuilder builder = new StringBuilder(ThreadLocalRandom.current().nextInt(0, 999)); // 随机数
builder.append(Math.abs(lock.hashCode()));// HASH-CODE
builder.AndIncrement());// ⾃增顺序
threadLocal.set(builder);
}
().toString();
}
/**
* 1000个线程并发测试
*
* @param args
* @throws InterruptedException
* @throws ExecutionException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
Set<String> set = new HashSet<String>();
FutureTask<String> task = null;
StopWatch watchTime = new StopWatch();
watchTime.start();
for (int i = 0; i < 1000; i++) {
Callable<String> callable = new Callable<String>() {
@Override
public String call() throws Exception {
// System.out.println("当前线程:>>>>> ".concat(Thread.currentThread().getId()+""));                    //return getC(null);
return getD(null);
}
};
task = new FutureTask<String>(callable);
new Thread(task).start();
set.());
System.out.());
}
watchTime.stop();
System.out.TotalTimeMillis());
System.out.println(set.size());
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。