iOS开发中遇到的几种多线程

最近整理了一下iOS开发中常用的几种多线程

// 第一种方式
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:@"test"]; [thread start];
// 第二种方式
[NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];
// 第三种方式
[self performSelectorInBackground:@selector(mutableThread) withObject:nil];
// 第四种方式
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperationWithBlock:^{   
     // 多线程上执行的方法
    }];

// 第五种方式
线程队列可以同时添加多个线程 可以设置优先级等

 NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];
    NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
     NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
    [threadQueue addOperation:op1];
    [threadQueue addOperation:op2];

// 第六种方式 GCD 这个性能最好 推荐使用这个

    dispatch_queue_create("test", NULL);
    dispatch_async(queue,  ^{
        // 多线程
        // 回到主线程执行
        dispatch_sync(dispatch_get_main_queue(), ^{
        这里写代码片// 主线程操作的代码
        });
    });
        return YES; 
        }

// 多线程执行的方法
注意!这边需要有一个自动释放池

- (void)mutableThread {
    @autoreleasepool {
 [self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:NO];
    } 
}

// 主线程

- (void)mianThread { 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值