您的位置:首页 > 其它

多线程学习06-线程安全

2016-04-19 14:39 183 查看
学习多线程06(之前跟着小码哥视频学习了多线程,准备把学到的东西放到网上,便于参考。仅有视频,所以所有文字都是自己打的,同时也温习一下多线程)

线程安全-互斥锁-线程同步

多线程的安全隐患

1,资源共享

1块资源可能会被多个线程共享,也就是多个线程可能会访问同一个资源;

比如多个线程访问同一个对象、同一个变量、同一个文件。

2,当多个线程访问同一块资源时,很容易引发数据错乱和数据安全问题;

博客原地址:/article/11543089.html

安全隐患解决-互斥锁

互斥锁使用格式

@synchronized (锁对象) { //需要锁定的代码 }
注意:锁定1份代码只用1把锁,用多把锁是无效的。
互斥锁的优缺点

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

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

使用前提:多条线程抢夺同一块资源。

相关专业术语:线程同步(同步不是同时,是同一条线程执行。默认是异步执行)

线程同步的意思是:多条线程在同一条线上执行(按顺序的执行任务)

问:如何使多条线程同步执行。加互斥锁@synchronized(self){ }

事例:

#import "ViewController.h"

@interface ViewController ()
/* 线程1 */
@property(nonatomic,strong)NSThread *thread1;
/* 线程2 */
@property(nonatomic,strong)NSThread *thread2;
/* 线程3 */
@property(nonatomic,strong)NSThread *thread3;
/* 票数 */
@property(nonatomic,assign)NSInteger ticketCount;

@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
self.ticketCount = 100;
self.thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread1.name = @"售票员01";
self.thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread2.name = @"售票员02";
self.thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];
self.thread3.name = @"售票员03";

}
/** 售票 */
-(void)saleTicket
{

while (1) {
@synchronized (self) {
NSInteger count = self.ticketCount;
if (count>0) {
self.ticketCount = count-1;
NSLog(@"%@卖了一张票,还剩下%zd张票",[NSThread currentThread].name,self.ticketCount);
}else
{
NSLog(@"票已经售完了");
break;
}
}

}

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
[self.thread1 start];
[self.thread2 start];
[self.thread3 start];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: