ios查看线程数量_iOS —— 多线程应用

一、共享资源

共享资源 : 就是内存中的一块资源同时被多个进程所访问,而每个进程可能会对该资源的数据进行修改

问题 : 如果 线程A 访问了某块资源 C,并且修改了其中的数据,此时 线程B 也访问了 资源C,并且也对 C 中的数据进行了修改;那么等到 线程A 和 线程B 执行结束后,此时,资源C 中的数据就并不是最初的设置了

如图

此时,如果用户想获取 被 线程A 修改的 资源C 的数据,但是 资源C 的数据也被 线程B 修改了,所以获得的是错误的数据;如果用户想获取 被 线程B 修改的 资源C 的数据,但是 资源C 的数据也被 线程A 修改了,所以获得的是错误的数据

下面看代码,以出售火车票为例

建立火车票数据模型

1 //LHTicketModal.h

2 #import

3

4 @interfaceLHTicketModal : NSObject5

6 @property (nonatomic) NSUInteger ticketCount; //剩余票数

7 @property (nonatomic) NSUInteger ticketSaleCount; //卖出数量

8

9 @end

10

11 //LHTicketModal.m

12 #import "LHTicketModal.h"

13

14 static const NSUInteger kTicketTotalCount = 50;15

16 @implementationLHTicketModal17

18 -(instancetype)init {19

20 self =[super init];21

22 if(self) {23

24 //初始化剩余票数应该为总数

25 _ticketCount =kTicketTotalCount;26

27 //初始化卖出票数应该为 0

28 _ticketSaleCount = 0;29

30 }31

32 returnself;33

34 }35

36 @end

UIViewController 代码,声明两个线程,分别代表两个地点

1 //LHSharedViewController.h

2 #import "LHSharedViewController.h"

3 #import "LHTicketModal.h"

4

5 @interfaceLHSharedViewController ()6

7 //车票模型

8 @property (nonatomic, strong) LHTicketModal *ticket;9

10 //线程对象

11 @property (nonatomic, strong) NSThread *threadBJ;12 @property (nonatomic, strong) NSThread *threadSH;13

14 @end

15

16 //LHSharedViewController.m

17 @implementationLHSharedViewController18

19 - (void)viewDidLoad {20

21 [super viewDidLoad];22

23 //1. 初始化 票数模型对象

24 _ticket =[[LHTicketModal alloc] init];25

26 //2. 初始化 线程对象 并设置线程名

27 _threadBJ = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets:) object:@"北京卖出"];28

29 _threadBJ.name = @"北京";30

31 _threadSH = [[NSThread alloc] initWithTarget:self selector:@selector(sellTickets:) object:@"上海卖出"];32

33 _threadSH.name = @"上海";34

35 }36

37 //线程执行的方法

38 - (void)sellTickets:(NSString *)str {39

40 while(YES) {41

42 //判断剩余量是否大于 0,大于 0 才可以卖出

43 if (_ticket.ticketCount > 0) {44

45 //暂停一段时间

46 [NSThread sleepForTimeInterval:0.2];47

48 //卖出一张票,剩余票数减 1,卖出票数加 1

49 _ticket.ticketCount--;50

51 _ticket.ticketSaleCount++;52

53 //获取当前进程

54 NSThread * currentThread =[NSThread currentThread];55

56 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);57

58 }59

60 }61

62 }63

64 //按钮的动作方法

65 - (IBAction)startSaleBtnClick:(id)sender {66

67 //开启线程

68 [_threadBJ start];69

70 [_threadSH start];71

72

73 }

点击按钮后,线程开始运行,结果如图

看一看出,共享资源同时被多个线程访问并修改,导致用户取得了错误的数据

那么解决这种情况的办法就是 加锁

加锁是指对一段代码进行加锁,加锁之后,若一个线程已经在对共享资源的数据修改,此时就不会再有其他线程来访问该资源进行修改,直至当前线程已经结束修改资源的代码时,其他进程才可以对其进行修改

可以把共享资源看做一个房间,线程看做人;当一个人进入房间之后就会锁门(加锁),对房间进行各种布置,此时其他人是进不来的,因为没有钥匙;直至当前的人出房间,其他的人才可以进房间进行布置

加锁的方式有多种,这里介绍两种

方式一 : 使用  @synchronized (加锁对象) {} 关键字

只需修改上述代码的  sellTickets 方法,其余不变,这里将其方法名改为  sellTickets_v2

1 - (void)sellTickets_v2:(NSString *)str {2

3 while(YES) {4

5 //对当前对象加锁

6 @synchronized (self) {7

8 //判断剩余量是否大于 0,大于 0 才可以卖出

9 if (_ticket.ticketCount > 0) {10

11 //暂停一段时间

12 [NSThread sleepForTimeInterval:0.2];13

14 //卖出一张票,剩余票数减 1,卖出票数加 1

15 _ticket.ticketCount--;16

17 _ticket.ticketSaleCount++;18

19 //获取当前进程

20 NSThread * currentThread =[NSThread currentThread];21

22 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);23

24 }25

26 }27

28 }29

30 }

再次运行程序,点击按钮。结果如图

方式二 : 使用 NSCondition 类

在 类扩展中声明并在 viewDidLoad 方法中初始化

1 - (void)sellTickets_v3:(NSString *)str {2

3 while(YES) {4

5 //使用 NSCondition 加锁

6 [_ticketCondition lock];7

8 //判断剩余量是否大于 0,大于 0 才可以卖出

9 if (_ticket.ticketCount > 0) {10

11 //暂停一段时间

12 [NSThread sleepForTimeInterval:0.2];13

14 //卖出一张票,剩余票数减 1,卖出票数加 1

15 _ticket.ticketCount--;16

17 _ticket.ticketSaleCount++;18

19 //获取当前进程

20 NSThread * currentThread =[NSThread currentThread];21

22 NSLog(@"%@ 卖了一张票,还剩 %lu 张票", currentThread.name, _ticket.ticketCount);23

24 }25

26 //使用 NSCondition 解锁

27 [_ticketCondition unlock];28

29 }30

31 }

运行结果和上述一样

使用 NSCondition 时,将加锁的代码放在 loac 和 unlock 中间

总结 :

1. 互斥锁的优缺点

优点 : 有效防止因多线程抢夺资源造成的数据安全问题

缺点 : 需要消耗大量 CPU 资源

2. 互斥锁使用的前提

多个线程抢夺同一资源

线程同步,互斥锁就是使用了线程同步

二、线程通信

通常, 一个线程不应该单独存在,应该和其他线程之间有关系

例如 : 一个线程完成了自己的任务后需要切换到另一个线程完成某个任务;或者 一个线程将数据传递给另一个线程

看代码,现在 xib 中拖入一个 按钮,并设置其动作方法,如下

1 - (IBAction)btn1Click:(id)sender {2

3 //1. 获取主线程

4 NSLog(@"mainThread --- %@", [NSThread mainThread]);5

6 //2. 创建子线程并完成指定的任务

7 [self performSelectorInBackground:@selector(run1:) withObject:@"子线程中执行方法"];8

9 }10

11 - (void)run1:(NSString *)str {12

13 //1. 获取当前线程

14 NSThread * currentThread =[NSThread currentThread];15

16 NSLog(@"currentThread --- %@ --- %@", currentThread, str);17

18 //2. 回到主线程中执行指定的方法

19 [self performSelectorOnMainThread:@selector(backMainThread:) withObject:@"回到主线程"waitUntilDone:YES];20

21 }22

23 - (void)backMainThread:(NSString *)str {24

25 //1. 获取当前线程(主线程)

26 NSThread * currentThread =[NSThread currentThread];27

28 NSLog(@"currentThread --- %@ --- %@", currentThread, str);29

30 }

这里通过 performSelectorInBackground: withObject: 方法创建一个子线程并完成指定的任务(run1:),然后在子线程中又通过

performSelectorOnMainThread: withObject: waitUntilDone: 方法回到主线程中完成指定的任务(backMainThread:)

点击按钮,运行结果如下

三、线程的状态

1. 当一个线程对象创建并开启后,它就会被放到线程调度池中,等待系统调度;如图

2. 当正在运行的线程被阻塞时,就会被移出 可调度线程池,此时不可再调度它

3. 当线程正常结束,异常退出,强制退出时都会导致该线程死亡,死亡的线程会从内存中移除,无法调度

代码如下

在 xib 中拖入一个 按钮,并设置其动作方法

1 #import "LHThreadStateViewController.h"

2

3 @interfaceLHThreadStateViewController ()4

5 @property (nonatomic, strong) NSThread *thread;6

7 @end

8

9 @implementationLHThreadStateViewController10

11 - (void)viewDidLoad {12

13 [super viewDidLoad];14

15 //1. 初始化线程对象

16 _thread = [[NSThread alloc] initWithTarget:self selector:@selector(runThread:) object:@"子线程执行任务"];17

18 _thread.name = @"线程A";19

20 }21

22 - (IBAction)startThreadClick:(id)sender {23

24 //1. 获取主线程

25 NSLog(@"mainThread --- %@", [NSThread mainThread]);26

27 //线程开始

28 [_thread start];29

30 }31

32 - (void)runThread:(NSString *)str {33

34 //1. 获取当前线程

35 NSThread * currentThread =[NSThread currentThread];36

37 NSLog(@"currentThread --- %@", currentThread);38

39 //2. 阻塞 2s

40 NSLog(@"线程开始阻塞 2s");41

42 [NSThread sleepForTimeInterval:2.0];43

44 NSLog(@"线程结束阻塞 2s");45

46 //3. 阻塞 4s

47 NSLog(@"线程开始阻塞 4s");48

49 //创建 NSDate 对象,并从当前开始推后 4s

50 NSDate * date = [NSDate dateWithTimeIntervalSinceNow:4.0];51

52 [NSThread sleepUntilDate:date];53

54 NSLog(@"线程结束阻塞 4s");55

56 //4. 退出线程

57 for (int i = 0; i < 10; ++i) {58

59 if (i == 7) {60

61 //结束当前线程,之后的语句不会再执行

62 [NSThread exit];63

64 NSLog(@"线程结束");65

66 }67

68 NSLog(@"%i --- %@", i, currentThread);69

70 }71

72 }

42 行使用 sleepForTimeInterval: 方法使得当前线程阻塞指定的时间

52 行使用 sleepUntilDate: 方法使得当前线程阻塞 参数中设定的时间;该参数必须是 NSDate 对象,并且以当前时间作为基准

62 行使用 exit 方法退出当前线程,并且退出后,该方法之后的语句不再会执行,上述中即 64 行代码不会执行

点击按钮,运行结果如下

注意 : 当 执行 exit 方法后,表示当前的线程已经死亡,即从内存中移除了,若此时再点击按钮(该线程在内存中已经没有空间了),程序会崩溃,并报以下的错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值