多线程(二)

接下来主要讲一下线程的创建和线程的安全问题

一、线程的创建(NSThread)

NSThread创建线程比较简单,主要有下面三种方式创建。

第一种

- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullable id)argument

第二种

- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullable id)arg

第三种

+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullable id)argument;

实践一

- (void)create_thread_first{
    NSThread * thread = [[NSThread alloc] initWithTarget:self selector:@selector(download:) object:@"create_thread_first"];
    thread.name = @"线程名字";
    [thread start];
}

- (void)download:(NSString *)url{
    
//    [NSThread sleepForTimeInterval:5];//休眠五秒
//    
//    NSDate * date = [NSDate dateWithTimeIntervalSinceNow:3];//休眠3秒
//    [NSThread sleepUntilDate:date];
    
    
     NSLog(@"%@--%@",url,[NSThread currentThread]);
}

实践一输出


实践二

- (void)create_thread_second{
    [self performSelectorInBackground:@selector(download:) withObject:@"create_thread_second"];
}

实践二输出


实践三

- (void)create_thread_third{
    [NSThread detachNewThreadSelector:@selector(download:) toTarget:self withObject:@"create_thread_third"];
}

实践三输出


二、线程安全

但凡涉及到这个问题,一般都是一个资源被多个线程共同访问,比如多个网点卖同一种类型的电影票,但电影票的总数一定,那么我们怎么才能控制多个网点共同访问电影票的问题呢——加锁,加锁便保证了线程安全。

- (void)thread_safety{
    
    self.leftCount = 50;
    
    self.threadOne = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.threadOne.name = @"threadOne";
    self.threadTwo = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.threadTwo.name = @"threadTwo";
    self.threadThree = [[NSThread alloc] initWithTarget:self selector:@selector(saleTicket) object:nil];
    self.threadThree.name = @"threadThree";
    
    [self.threadOne start];
    [self.threadTwo start];
    [self.threadThree start];
    
}
- (void)saleTicket{
    while (1) {
        @synchronized(self) {//加锁,保证线程安全
            if (self.leftCount > 0) {
                self.leftCount --;
                 NSLog(@"%@卖了一张票,剩余%d张票",[NSThread currentThread].name,self.leftCount);
            }else{
                return;//退出线程
            }
        }
    }
}

那么输出结果如下



上面可能只是简单的例子,我要做的是抛砖引玉。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值