File tree Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Expand file tree Collapse file tree 1 file changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ package chapter4 ;
2+
3+ import java .util .concurrent .atomic .AtomicReference ;
4+
5+ /**
6+ * Created by 13 on 2017/5/6.
7+ */
8+ public class AtomicRefrenceDemo {
9+
10+ //运行中可能不会出现书中提到的情况
11+ public static void main (String args []) {
12+ final AtomicReference <Integer > money = new AtomicReference <Integer >();
13+ money .set (19 );
14+
15+ for (int i = 0 ; i < 100 ; i ++) {
16+ new Thread () {
17+ public void run () {
18+ while (true ) {
19+ Integer m = money .get ();
20+ if (m < 20 ) {
21+ if (money .compareAndSet (m , m + 20 )) {
22+ System .out .println ("余额小于20元,充值成功,余额:" + money .get () + "元" );
23+ break ;
24+ }
25+ } else {
26+ System .out .println ("余额大于20,无需充值" );
27+ break ;
28+ }
29+ }
30+ }
31+ }.start ();
32+ }
33+
34+ new Thread () {
35+ public void run () {
36+ for (int i = 0 ; i < 100 ; i ++) {
37+
38+ while (true ) {
39+ Integer m = money .get ();
40+ if (m > 10 ) {
41+ System .out .println ("金额大于10元" );
42+ if (money .compareAndSet (m , m - 10 )) {
43+ System .out .println ("成功消费10元,余额:" + money .get () + "元" );
44+ break ;
45+ }
46+ } else {
47+ System .out .println ("没有足够的金额" );
48+ break ;
49+ }
50+ }
51+ try {
52+ Thread .sleep (100 );
53+ } catch (InterruptedException e ) {
54+ e .printStackTrace ();
55+ }
56+ }
57+ }
58+ }.start ();
59+ }
60+ }
You can’t perform that action at this time.
0 commit comments