多线程

线程:

{

    NSInteger _count;
    //锁
    NSLock *_lock;

}

 _lock=[[NSLock alloc] init];  //在didload里边初始化_lock


第一种:

    NSThread *thred1=[[NSThread alloc]initWithTarget:self selector:@selector(sum) object:nil];
    
    //给你的线程起个名字
    thred1.name=@"thred1";
    //启动线程
    [thred1 start];
    //关闭线程
    [thred1 cancel];

第二种(不需要手动开启的)

 [NSThread detachNewThreadSelector:@selector(sum) toTarget:self withObject:nil];

第三种继承与NSObject方式

[self performSelectorInBackground:@selector(sum) withObject:nil];

线程里边执行的方法

//要在线程中执行的方法
-(void)sum{
    long long sum=0;
    
    for (long long i=0; i<635500000; i++) {
        
        NSLog(@"线程:%@ %lld",[NSThread currentThread],sum+=i);
    }

    NSLog(@"结束了");
   

}

简单售票多线程

//票数
    _count=20;
    
    //线程
    NSThread *thred11=[[NSThread alloc] initWithTarget:self selector:@selector(saleticket) object:nil];
    
    thred11.name=@"售票1";
    
    [thred11 start];
    
    NSThread *thred22=[[NSThread alloc] initWithTarget:self selector:@selector(saleticket) object:nil];
    thred22.name=@"售票2";
    [thred22 start];

执行方法

//卖票的方法
-(void)saleticket{

    while (YES) {
        [_lock lock];
        if (_count > 0) {
           
            NSLog(@"%@ : 当前票数 %d", [NSThread currentThread],_count--);
            //延迟
            sleep(1);
            [_lock unlock];
        }else{
        
            NSLog(@"票以售完");
            break;
        
        }
        
    }


}

 NSOperation

有两个子类   NSInvocationOperation   NSBlockOperation .

NSOperationQueue  是操作队列,他用来管理一组Operation对象的执行,会根据需要自动为Operation开辟合适数量的线程,以完成任务的并行执行.



    // NSOperation
    NSInvocationOperation *inOP=[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(invocation) object:nil];
    
  //  [inOP start];
    
    //
    NSBlockOperation *blOp=[NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"我是Block");
    }];
    

    
    //创建队列
    NSOperationQueue *queue=[[NSOperationQueue alloc] init];
    
    //设置最大同时执行数量
    queue.maxConcurrentOperationCount=3;
    
    //添加事件(先进先出)
    [queue addOperation:inOP];
    [queue addOperation:blOp];

方法

-(void)invocation{

   // NSLog(@"%@",[NSThread currentThread]);

    NSLog(@"我是方法");
}





评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值