forked from pro648/BasicDemos-iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBaseDemo2.m
More file actions
100 lines (72 loc) · 1.87 KB
/
Copy pathBaseDemo2.m
File metadata and controls
100 lines (72 loc) · 1.87 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
//
// BaseDemo2.m
// Synchronization
//
// Created by pro648 on 2020/5/8.
// Copyright © 2020 pro648. All rights reserved.
//
#import "BaseDemo2.h"
@interface BaseDemo2 ()
@property (nonatomic, assign) int ticketsCount;
@property (nonatomic, assign) int money;
@end
@implementation BaseDemo2
// MARK: - Money
- (void)moneyTest {
self.money = 100;
dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_UTILITY, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 10; ++i) {
[self __saveMoney];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 10; ++i) {
[self __drawMoney];
}
});
}
- (void)__drawMoney {
int oldMoney = self.money;
sleep(1);
oldMoney -= 20;
self.money = oldMoney;
NSLog(@"取20元,还剩%d元 -- %@", oldMoney, [NSThread currentThread]);
}
- (void)__saveMoney {
int oldMoney = self.money;
sleep(1);
oldMoney += 50;
self.money = oldMoney;
NSLog(@"存50元,还剩%d元 -- %@", oldMoney, [NSThread currentThread]);
}
// MARK: - Sale Ticket
- (void)ticketTest {
self.ticketsCount = 15;
dispatch_queue_t queue = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0);
dispatch_async(queue, ^{
for (int i = 0; i < 5; ++i) {
[self __saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 5; ++i) {
[self __saleTicket];
}
});
dispatch_async(queue, ^{
for (int i = 0; i < 5; ++i) {
[self __saleTicket];
}
});
}
- (void)__saleTicket {
int oldTicketsCount = self.ticketsCount;
sleep(1);
oldTicketsCount--;
self.ticketsCount = oldTicketsCount;
NSLog(@"还剩%d张票 -- %@", oldTicketsCount, [NSThread currentThread]);
}
- (void)otherTest {
}
@end