多线程常用方法总结

NSThread

开线程的三种方法

 1. [[NSThread alloc]initWithTarget:self selector:@selector(run:) object:@"dd"]

 2. [self performSelectorInBackground:@selector(run:) withObject:@"dd"]

 3. [NSThread detachNewThreadSelector:@selector(run:) toTarget:self withObject:@"dd"]

object是run函数的参数。


GCD

创建队列

 1. dispatch_queue_t queue = dispatch_get_main_queue();//获得主线程串行队列

 2. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);//获得全局并发队列

 3. dispatch_queue_t queue = dispatch_queue_create("aaa", DISPATCH_QUEUE_CONCURRENT);//创建一个新队列,第一个参数为唯一标识符,第二个是指定队列是并发还是串行

添加任务

 1. dispatch_async(queue, ^{
        NSLog(@"----下载图片1----%@", [NSThread currentThread]);
    });//添加异步任务

 2. dispatch_sync(queue, ^{
        NSLog(@"----下载图片2----%@", [NSThread currentThread]);
    });//添加同步任务

NSOperation

三种添加任务的方法

 1. NSBlockOperation *operation = [[NSBlockOperation alloc]init];
    [operation addExecutionBlock:^{
        NSLog(@"----下载图片1----%@", [NSThread currentThread]);
    }];

 2. NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{
        NSLog(@"----下载图片2----%@", [NSThread currentThread]);
    }];

 3. NSInvocationOperation *operation1 = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(run:) object:@"aaa"];

队列

1. NSOperationQueue *queue = [[NSOperationQueue alloc]init];//初始化队列
2. queue.maxConcurrentOperationCount = 2;//设置当前最大操作数
3. [operation addDependency:operation1];//设置操作依赖
4. [queue addOperation:operation];//队列添加操作
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值