ios线程篇:多线程的几种创建方式


<span style="font-size:14px;color:#cc0000;"><strong>- (void)viewDidLoad {
    
    // 创建方式一
    NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
    
    // 创建方式二 直接开辟并且执行
    [NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
    
    // 创建方式三
    [self performSelectorInBackground:@selector(run) withObject:nil];
    
    // 创建方式四
    NSOperationQueue* operation = [[NSOperationQueue alloc] init];
    operation.maxConcurrentOperationCount = 1;//指定池子的并发数
    
    // 任务A
    NSInvocationOperation* invation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
    // 任务B
    NSInvocationOperation* invation1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(run) object:nil];
    //设置线程优先级
    invation.queuePriority = NSOperationQueuePriorityHigh;
    //将任务添加到池子里面,可以给池子添加多个任务,并且指定它的并发数
    [operation addOperation:invation];
    [operation addOperation:invation1];
    
    // 第五种方式
    NSOperationQueue* operationQueue = [[NSOperationQueue alloc] init];
    [operationQueue addOperationWithBlock:^{
        //这个block语句块在子线程中执行
        NSLog(@"START");
    }];
    
    // 第六种方式
    // 调用主线程,用于子线程和主线程的交互,最后面的那个done参数如果为yes就是等这个方法执行完了在执行
    [self performSelectorOnMainThread:@selector(run) withObject:nil waitUntilDone:YES];
    
    // 第六种方式
    //--------------GCD----------支持多核,高效率的多线程技术
    dispatch_queue_t queue = dispatch_queue_create("name", NULL);
    dispatch_async(queue, ^{
        NSLog(@"创建一个异步子线程");
        // 执行点什么
        dispatch_async(dispatch_get_main_queue(), ^{
            
            NSLog(@"回到主线程 %@",[NSThread currentThread]);
            
        });
    });
    
    [super viewDidLoad];

}

- (void)run
{
    NSLog(@"多线程运行!");
}</strong></span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值