IOS-多线程

来源:互联网 发布:c语言&.2f是什么意思 编辑:程序博客网 时间:2024/06/15 22:21

NSThread简单的线程同步

这里写代码片@interface FZViewController ()@property (nonatomic, assign) int leftTicksNum;@property (nonatomic, strong) NSThread *thread1;@property (nonatomic, strong) NSThread *thread2;@property (nonatomic, strong) NSThread *thread3;@end@implementation FZViewController- (void)viewDidLoad{    [super viewDidLoad];    self.leftTicksNum = 10;    self.thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTick) object:nil];    self.thread1.name  = @"thread1";    self.thread2 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTick) object:nil];    self.thread2.name  = @"thread2";    self.thread3 = [[NSThread alloc] initWithTarget:self selector:@selector(saleTick) object:nil];    self.thread3.name  = @"thread3";}- (void)saleTick{    NSThread *thread = [NSThread currentThread];    while (1) {        @synchronized(self) {            if (self.leftTicksNum <= 0) break;            [NSThread sleepForTimeInterval:(arc4random() % 10) * 0.1];            NSLog(@"当前还剩:%d %@售出一张,还剩:%d张", self.leftTicksNum, thread.name, self.leftTicksNum - 1);            self.leftTicksNum--;        }    }    [NSThread exit];}- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{    [self.thread1 start];    [self.thread2 start];    [self.thread3 start];}@end
0 0