java实现qq抢红包_Java实现抢红包功用
用多線程模仿多人一起搶紅包。服務端將玩家發出的紅包保存在一個行列里,然后用Job守時將紅包信息推送給玩家。每一批玩家的搶紅包懇求,其實操作的都是從行列中彈出的第一個紅包元素,但當時的紅包數量為空的時分,主動彈出下一個紅包(如果有的話)。
關鍵思維:
1.搶紅包涉及多人并發操作,需求做好同步保證多線程運行結果正確。
2.因為一起在線人數大,從功能方面考慮,玩家的發紅包懇求不必及時響應,而由服務端守時履行發紅包行列。
下面是主要的代碼和完成邏輯闡明
1.創建一個類,表示紅包這個實體概念。直接選用原子變量保證增減同步。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();
}
}
}
總結
以上是生活随笔為你收集整理的java实现qq抢红包_Java实现抢红包功用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vb.net读取excel并写入dgv_
- 下一篇: java美元兑换,(Java实现) 美元