亚洲精品一区二区手机在线观看,久久久久久夜,国产精品人人爽97欧美视频,超碰人人婷婷,国产剧免费观看高清电视剧,99av亚洲综合一区二区,91精品欧美久久久久,久久婷婷五月综合色D啪

Java實現搶紅包功用

時間:2023-05-16

用多線程模仿多人一起搶紅包。服務端將玩家發出的紅包保存在一個行列里,然后用Job守時將紅包信息推送給玩家。每一批玩家的搶紅包懇求,其實操作的都是從行列中彈出的第一個紅包元素,但當時的紅包數量為空的時分,主動彈出下一個紅包(如果有的話)。
關鍵思維:
1.搶紅包涉及多人并發操作,需求做好同步保證多線程運行結果正確。
2.因為一起在線人數大,從功能方面考慮,玩家的發紅包懇求不必及時響應,而由服務端守時履行發紅包行列。
下面是主要的代碼和完成邏輯闡明
1.創建一個類,表示紅包這個實體概念。直接選用原子變量保證增減同步。Java的原子變量是一種精度更細的同步機制,在高度競賽的狀況下,鎖的功能將超過原子變量的功能,但在更真實的競賽狀況,原子變量享有更好的功能。Java

publicclassSpringGift{
privateStringrole;
privateAtomicIntegergift;
publicStringgetRole(){
returnrole;
}
publicvoidsetRole(Stringrole){
this.role=role;
}
publicAtomicIntegergetGift(){
returngift;
}
publicvoidsetGift(AtomicIntegergift){
this.gift=gift;
}
publicintgetRemainCount(){
returnthis.gift.get();
}
}
2.選用多線程模仿多人一起搶紅包。服務端將玩家發出的紅包保存在一個行列里,然后用Job守時將紅包信息推送給玩家。每一批玩家的搶紅包懇求,其實操作的都是從行列中彈出的第一個紅包元素,但當時的紅包數量為空的時分,主動彈出下一個紅包(如果有的話)。
publicclassTest{
publicstaticConcurrentLinkedQueuequeue;
publicstaticSpringGiftcurrGift;
publicstaticAtomicIntegercount=newAtomicInteger();
staticclassmyThreadimplementsRunnable{
publicvoidrun(){
handleEvent();
}
}
publicstaticvoidmain(String[]args)throwsException{
queue=newConcurrentLinkedQueue();
for(inti=0;i<3;i++){
SpringGiftgift=newSpringGift();
gift.setRole(“role”+i);
gift.setGift(newAtomicInteger(50));
queue.add(gift);
}
myThreadmythread=newmyThread();
for(inti=0;i<1000;i++){
newThread(mythread).start();
}
System.err.println(“一共收到”+count.get());
}
privatestaticSpringGiftgetGift(){
//防止多條線程一起彈出隊首
synchronized(queue){//若沒有加鎖,打印的count總數不對!!!!
if(currGift==null||currGift.getRemainCount()<=0){
currGift=queue.poll();
}
}
returncurrGift;
}
publicstaticvoidhandleEvent(){
try{
SpringGiftobj=getGift();
if(obj==null||obj.getRemainCount()<=0){
System.err.println(“沒有了”);
return;
}
if(obj!=null&&obj.getGift().getAndDecrement()>0){
System.err.println(“搶到一個紅包”);
count.getAndIncrement();
}
Thread.sleep(500);//模仿處理其他操作
}catch(Exceptione){
e.printStackTrace();
}
}
}

文章標簽:

Copyright ? 2016 廣州思洋文化傳播有限公司,保留所有權利。 粵ICP備09033321號

與項目經理交流
掃描二維碼
與項目經理交流
掃描二維碼
與項目經理交流
ciya68