本文實例為大家分享了java實現搶紅包功能的具體代碼,供大家參考,具體內容如下
關鍵思想:
1.搶紅包涉及多人并發操作,需要做好同步保證多線程運行結果正確。
2.由于同時在線人數大,從性能方面考慮,玩家的發紅包請求不必及時響應,而由服務端定時執行發紅包隊列。
下面是主要的代碼和實現邏輯說明
1.創建一個類,表示紅包這個實體概念。直接采用原子變量保證增減同步。java的原子變量是一種精度更細的同步機制,在高度競爭的情況下,鎖的性能將超過原子變量的性能,但在更真實的競爭情況,原子變量享有更好的性能。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class springgift { private string role; private atomicinteger gift; public string getrole() { return role; } public void setrole(string role) { this .role = role; } public atomicinteger getgift() { return gift; } public void setgift(atomicinteger gift) { this .gift = gift; } public int getremaincount(){ return this .gift.get(); } } |
2.采用多線程模擬多人同時搶紅包。服務端將玩家發出的紅包保存在一個隊列里,然后用job定時將紅包信息推送給玩家。每一批玩家的搶紅包請求,其實操作的都是從隊列中彈出的第一個紅包元素,但當前的紅包數量為空的時候,自動彈出下一個紅包(如果有的話)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
public class test { public static concurrentlinkedqueue<springgift> queue; public static springgift currgift; public static atomicinteger count = new atomicinteger(); static class mythread implements runnable{ public void run(){ handleevent(); } } public static void main(string[] args) throws exception { queue = new concurrentlinkedqueue<springgift>(); for ( int i = 0 ;i< 3 ;i++){ springgift gift = new springgift(); gift.setrole( "role" +i); gift.setgift( new atomicinteger( 50 )); queue.add(gift); } mythread mythread = new mythread(); for ( int i= 0 ;i< 1000 ;i++){ new thread(mythread).start(); } system.err.println( "總共收到" +count.get()); } private static springgift getgift(){ //防止多條線程同時彈出隊首 synchronized (queue) { //若沒有加鎖,打印的count總數不對!!!! if (currgift == null || currgift.getremaincount() <= 0 ){ currgift = queue.poll(); } } return currgift; } public static void handleevent(){ try { springgift obj = 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 (exception e){ e.printstacktrace(); } } } |
運行結果部分截圖如下
需要注意的是,getgift()這個方法,由于是自動彈出隊首元素,必須做好同步機制,否則,當多個請求同時操作某一個紅包的最后一次剩余時,會造成總的紅包數量不正確。
(將加鎖的代碼注釋后,會發現打印的總數量有可能不正確了!)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/littleschemer/article/details/46382117