1、 源程序;
1、 packagecom.sinosuperman.memcached;;
2、 ;
3、 importjava.io.IOException;;
4、 importjava.net.InetSocketAddress;;
5、 ;
6、 importnet.spy.memcached.CASResponse;;
7、 importnet.spy.memcached.CASValue;;
8、 importnet.spy.memcached.MemcachedClient;;
9、 ;
10、 ;
11、 public****classTest{;
12、 ;
13、 private****staticMemcachedClientclient=null;;
14、 ;
15、 static{;
16、 try{;
17、 client=newMemcachedClient(newInetSocketAddress(“localhost”,11211));;
18、 }catch(IOExceptiono){;
19、 };
20、 };
21、 ;
22、 publicstaticvoidmain(String[]args)throwsException{;
23、 ;
24、 client.set(“numberss”,1800,1);;
25、 ;
26、 TesttestObj=newTest();;
27、 for(inti=0;i<10;i++){;
28、 testObj.newThreadTest(“Thread-"+(i+1)).start();;
29、 };
30、 };
31、 ;
32、 private****classThreadTestextendsThread{;
33、 ;
34、 privateMemcachedClientclient=null;;
35、 ThreadTest(Stringname)throwsIOException{;
36、 super(name);;
37、 client=newMemcachedClient(newInetSocketAddress(“localhost”,11211));;
38、 };
39、 ;
40、 public****voidrun(){;
41、 inti=0;;
42、 intsuccess=0;;
43、 while(i<10){;
44、 i++;;
45、 CASValueuniqueValue=client.gets(“numberss”);;
46、 CASResponseresponse=client.cas(“numberss”,;
47、 uniqueValue.getCas(),(Integer)uniqueValue.getValue()+1);;
48、 ;
49、 if(response.toString().equals(“OK”)){;
50、 success++;;
51、 };
52、 ;
53、 if(i==10);
54、 System.out.println(Thread.currentThread().getName()+”"+i;
55、 +“time”+“updateoldValue:"+uniqueValue.getValue();
56、 +",result:"+response);;
57、 };
58、 ;
59、 if(success<10){;
60、 Count.incr(10-success);;
61、 System.out.println(“Testcounter:"+Count.get());;
62、 };
63、 };
64、 };
65、 ;
66、 publicstaticclassCount{;
67、 privatestaticintcounter=0;;
68、 publicstaticvoidincr(intx){;
69、 counter+=x;;
70、 };
71、 publicstaticintget(){;
72、 returncounter;;
73、 };
74、 };
75、 };
2、 输出结果:;
1、 Thread-110timeupdateoldValue:14,result:EXISTS;
2、 Testcounter:6;
3、 Thread-210timeupdateoldValue:14,result:EXISTS;
4、 Testcounter:15;
5、 Thread-310timeupdateoldValue:17,result:EXISTS;
6、 Testcounter:22;
7、 Thread-510timeupdateoldValue:17,result:EXISTS;
8、 Testcounter:27;
9、 Thread-410timeupdateoldValue:20,result:OK;
10、 Testcounter:33;
11、 Thread-810timeupdateoldValue:27,result:OK;
12、 Testcounter:36;
13、 Thread-610timeupdateoldValue:28,result:EXISTS;
14、 Testcounter:43;
15、 Thread-1010timeupdateoldValue:31,result:EXISTS;
16、 Testcounter:52;
17、 Thread-910timeupdateoldValue:31,result:OK;
18、 Testcounter:60;
19、 Thread-710timeupdateoldValue:35,result:OK;
20、 Testcounter:65;
3、 分析;
我们可以看到,未成功的次数最终为65,数据值最终为35,两者的和刚好是100,正好符合我们的实验结果预期。
版权声明:本文为博主原创文章,未经博主允许不得转载。
版权声明:本文不是「本站」原创文章,版权归原作者所有 | 原文地址:
上一篇:18、MemCached实战:Memcached的一些基础FAQ
下一篇:16、MemCached实战:Memcached的CAS程序实例
阅读全文
江小北的笔记 AIJIANGSIR.COM -沪ICP备2023041623号-1