线程安全(互斥锁)-7

2016-06-02  本文已影响44人  Sunney

多线程的安全隐患

资源共享

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

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

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

解决方法

互斥锁使用格式

@synchronized(所对象){

//需要锁定的代码

注意:锁定1份代码只用1把锁,用多把锁是无效的

互斥锁的优缺点:

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

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

互斥锁的使用前提:多条线程抢夺同一块资源

专业术语:线程同步

线程同步:多线程在同一条线上执行(按顺序地执行任务)

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

}

@property (nonatomic, strong) NSThread *thread1;

@property (nonatomic, strong) NSThread *thread2;

@property (nonatomic, strong) NSThread *thread3;

@property (nonatomic, assign) NSInger ticketCount;

@property (nonatomic,strong) NSOject *locker;

- (void)viewDidLoad{

[super viewDidLoad];

self.ticketCount = 100;

self.locker = [[NSObject alloc]init];

self.thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread1.name = @"售票员1";

self.thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread2.name = @"售票员2";

self.thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(saleTicket) object:nil];

self.thread3.name = @"售票员3";

}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

[slef.thread1 start];

[self.thread2 start];

[self.thread3 start];

}

 - (void)saleTicket{

@synchronized(self){

while(1){

//先取出票

NSInteger count = self.ticketCount;

if(count > 0){

self.ticketCount = count - 1;

NSLog(@"%@买了一张票,还剩下%ld张",[NSThread currentThread].name,self.ticketCount);

}else{

NSLog(@"票已经卖完了");

break;0

}

}

}

}

上一篇 下一篇

猜你喜欢

热点阅读