线程锁-生产者与消费者
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong) NSLock *lock;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建了一个线程锁
self.lock = [[NSLock alloc]init];
NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(eat) object:nil];
thread1.name = @"夏洛";
[thread1 start];
NSThread *thread2 = [[NSThread alloc]initWithTarget:self selector:@selector(eat) object:nil];
thread2.name = @"马冬梅";
[thread2 start];
NSThread *thread3 = [[NSThread alloc]initWithTarget:self selector:@selector(eat) object:nil];
thread3.name = @"秋雅";
[thread3 start];
}
- (void)eat{
static int num = 5;
while (1) {
//加锁之后 同一时刻只允许一个线程访问
//加锁 数据修改之前
[self.lock lock];
num --;
NSLog(@"%@吃了一碗茴香打卤面 还剩……%d碗",[NSThread currentThread].name,num);
[NSThread sleepForTimeInterval:2.f];
if (num == 0) {
break;
}
//解锁 数据修改完成
[self.lock unlock];
}
}
@end
屏幕快照 2019-04-25 下午3.34.05.png
网友评论