志在指尖
用双手敲打未来

Java实现抢红包功用

用多线程模仿多人一起抢红包。服务端将玩家发出的红包保存在一个行列里,然后用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();
}
}
}

未经允许不得转载:IT技术网站 » Java实现抢红包功用
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!

 

志在指尖 用双手敲打未来

登录/注册IT技术大全

热门IT技术

C#基础入门   SQL server数据库   系统SEO学习教程   WordPress小技巧   WordPress插件   脚本与源码下载