ios多线程

来源:互联网 发布:淘宝女装店铺top排行榜 编辑:程序博客网 时间:2024/05/21 06:56

创建多线程的方法有:NSThread、NSOperation和GCD三种

// 1、显性线程

- (void)thread1
{
    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(loadImage) object:nil];
    [thread start];
}
// 2、静态线程
- (void)thread2
{
    [NSThread detachNewThreadSelector:@selector(loadImage) toTarget:self withObject:nil];
}

// 3、隐性线程
- (void)thread3
{
    [self performSelectorInBackground:@selector(loadImage) withObject:nil];
}

// 4、NSOperation NSQueue
- (void)thread4
{
    NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(loadImage) object:nil];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperation:operation];
    
    
}
// 5、GCD

// 5.1、传统的单一线程
- (void)singleGCD
{
    dispatch_queue_t queue = dispatch_get_main_queue();

    dispatch_async(queue, ^{
    
        // 主线程刷新UI
        dispatch_async(dispatch_get_main_queue(), ^{
            
        });
    });
}
// 5.2、如果想在dispatch_queue中所有的任务执行完成后在做某种操作,在串行队列中,可以把该操作放到最后一个任务执行完成后继续,但是在并行队列中怎么做呢。这就有dispatch_group 成组操作
- (void)groupGCD
{
    dispatch_queue_t queue = dispatch_get_main_queue();
    dispatch_group_t dispatchGroup = dispatch_group_create();
    dispatch_group_async(dispatchGroup, queue, ^{
        NSLog(@"thread1");
    });
    dispatch_group_async(dispatchGroup, queue, ^{
        NSLog(@"thread2");
    });
    dispatch_group_notify(dispatchGroup, queue, ^{
        NSLog(@"notify");
    });
    
    
}
// 5.3、dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的,这就意味着你不需要使用诸如@synchronized之类的来防止使用多个线程或者队列时不同步的问题。

/*
如果你要共享某个实例

+(MyInstance*)shareMyInstance()



static MyInstance *inst=nil;

static dispatch_once_t   p;

dispatch_once(&p,^{
    
    inst=[[MyInstance alloc]init];
    
});

return inst;


*/
// 5.4、延迟2秒执行:
- (void)afterGCD
{
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        // code to be executed on the main queue after delay
    });
}


// 5.5、自定义dispatch_queue_t
- (void)customGCD
{
    dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);
    dispatch_async(urls_queue, ^{
        
    });
}

0 0