IOS教程

iOS基础 - 线程:训练营(模拟两窗口售票)

本文主要是介绍iOS基础 - 线程:训练营(模拟两窗口售票),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

设计思路

1 - 多窗口售票,就要考虑到防止线程之间抢占公共资源(票)

2 - 代码示例:线程锁

 1 #import "ViewController.h"
 2 @interface ViewController (){
 3 
 4    
 5     NSInteger _TCNumber;     // 总票数
 6     NSInteger _ticketsCount; // 剩余票数
 7     NSLock * _threadLock;    // 线程锁
 8 }
 9 
10 @end
11 
12 @implementation ViewController
13 
14 - (void)viewDidLoad {
15     [super viewDidLoad];
16     
17     _TCNumber = 500;
18     _ticketsCount = _TCNumber;
19     _threadLock = [[NSLock alloc] init];
20     NSLog(@"%@",_threadLock);
21     
22     // 窗口售票
23     [self saleTicketsWindow];
24     
25 }
26 
27 
28 // 两个售票窗口:开启子线程
29 - (void)saleTicketsWindow{
30 
31     NSThread * thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(makeSaled) object:nil];
32     thread1.name = @"窗口A";
33 
34     NSThread * thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(makeSaled) object:nil];
35     thread2.name = @"窗口B";
36 
37     [thread1 start];
38     [thread2 start];
39 
40 }
41 
42 // 售票
43 - (void)makeSaled{
44 
45     while (1) {
46         [_threadLock lock];// 上锁
47         
48         if (_ticketsCount > 0) {
49 
50             _ticketsCount --;// 出票
51             NSInteger saleCount = _TCNumber - _ticketsCount;// 卖出张数
52             NSLog(@"售出:%ld 剩余:%ld %@卖出的",(long)saleCount,(long)_ticketsCount,[NSThread currentThread].name);
53             [_threadLock unlock];// 解开
54         }
55     }
56 }
57 
58 @end

日志打印

 

这篇关于iOS基础 - 线程:训练营(模拟两窗口售票)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!