private final AtomicLong seed;
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
*/
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
閒來無事,想如果自己設計微信紅包,怎麼設計呢?
因爲我不是微信紅包的開發人員,所以以下內容純屬虛構
先說下我的算法,每人隨機一個數,然後把所有人的加起來成爲分母,每個人的數是分子,分子除以分母,就是這個人佔用紅包的額度。
直接看代碼
public class Haobao {
public static List<Integer> buildFen(int fen,int i){
if(fen<=i){
return null;
}
List<Integer> ins=new ArrayList<Integer>(i);
List<Integer> cns=new ArrayList<Integer>(i);
// Random r=ThreadLocalRandom.current();
Random r=new Random();
int total=0;
for(int j=0;j<i;j++){
int c=r.nextInt(i*10)+1;
total=total+c;
ins.add(c);
}
BigDecimal t=new BigDecimal(total);
BigDecimal f=new BigDecimal(fen);
BigDecimal s=f.divide(t,4,BigDecimal.ROUND_DOWN);
for(int j=0;j<i-1;j++){
int c=s.multiply(new BigDecimal(ins.get(j))).intValue();
if(c==0||(fen-c)<(i-j)){
c=1;
}
fen=fen-c;
cns.add(c);
}
cns.add(fen);
return cns;
}
public static void main(String[] args){
for(int k=0;k<10;k++){
long begin=System.currentTimeMillis();
for(int i=0;i<10*10000;i++){
List<Integer> s=buildFen(2245, 100);
// System.out.println(s.toString());
}
System.out.println("time:"+(System.currentTimeMillis()-begin));
}
}
}
Random VS ThreadLocalRandom
有人說ThreadLocalRandom 性能比Random高,有人說Random線程不安全。
今天就看下源碼,本人看的是JDK 1.7的
先看Random的,關鍵是seed因子
private final AtomicLong seed;
private static final long multiplier = 0x5DEECE66DL;
private static final long addend = 0xBL;
private static final long mask = (1L << 48) - 1;
/**
* Creates a new random number generator. This constructor sets
* the seed of the random number generator to a value very likely
* to be distinct from any other invocation of this constructor.
*/
public Random() {
this(seedUniquifier() ^ System.nanoTime());
}
再看下ThreadLocalRandom ,首先ThreadLocalRandom 繼承了Random,仔細看接口,一些方法都是重用父類的。
用TheadLocal 實現的線程安全。
private static final ThreadLocal<ThreadLocalRandom> localRandom =
new ThreadLocal<ThreadLocalRandom>() {
protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom();
}
};