java实现qq抢红包_Java实现抢红包功用

用多线程模仿多人一起抢红包。服务端将玩家发出的红包保存在一个行列里,然后用Job守时将红包信息推送给玩家。每一批玩家的抢红包恳求,其实操作的都是从行列中弹出的第一个红包元素,但当时的红包数量为空的时分,主动弹出下一个红包(如果有的话)。

关键思维:

1.抢红包涉及多人并发操作,需求做好同步保证多线程运行结果正确。

2.因为一起在线人数大,从功能方面考虑,玩家的发红包恳求不必及时响应,而由服务端守时履行发红包行列。

下面是主要的代码和完成逻辑阐明

1.创建一个类,表示红包这个实体概念。直接选用原子变量保证增减同步。Java的原子变量是一种精度更细的同步机制,在高度竞赛的状况下,锁的功能将超过原子变量的功能,但在更真实的竞赛状况,原子变量享有更好的功能。f310ad455d2549801a6518c52fc9ad6f.png

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();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值