多線程實現(xiàn)的幾種方案,主要包括pthread、NSThread、GCD、NSOperation。PS:其中pthread和NSThread需要我們管理線程生命周期,比較麻煩,不是很常用,我們重點關(guān)注GCD和NSOperation。This is Operation。
NSOperation的核心將操作添加到隊列中,是對GCD技術(shù)的一種面向?qū)ο蟮膶崿F(xiàn)方式。NSOperation是一個抽象類,通過其子類NSInvocationOperation和NSBlockOperation來實現(xiàn)。
- NSOperation常用方法,start,cancel
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(uploadAction) object:nil];
// 開始執(zhí)行任務(wù)
[operation start];
// 取消任務(wù)
[operation cancel];
- NSInvocationOperation,比較適合操作較復(fù)雜代碼比較多的場景
NSInvocationOperation *operation = [[NSInvocationOperation alloc]initWithTarget:self selector:@selector(loadImage) object:nil];
// 開始執(zhí)行任務(wù)
[operation start];
- (void)loadImage{
dispatch_queue_t queue = dispatch_queue_create("com.silence.tongbu.mySerialQueue",DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
// 耗時操作,加載一張圖片
NSURL *url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1523902227523&di=474686c26c7a7d2b815305dd45f0e046&imgtype=0&src=http%3A%2F%2Fcdnq.duitang.com%2Fuploads%2Fitem%2F201504%2F30%2F20150430125352_aeTLk.jpeg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
NSLog(@"任務(wù)A:獲取圖片==》%@,當(dāng)前線程==》%@",image,[NSThread currentThread]);
});
}
- NSBlockOperation,比較適合操作簡單代碼少的場景
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"一個簡單的任務(wù)");
}];
[operation start];
- NSOperationQueue操作隊列,管理多個并發(fā)任務(wù)。多個操作添加到隊列中,自動執(zhí)行。
// 1 創(chuàng)建隊列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 2 創(chuàng)建多個操作
for (int i = 0; i < 10; i++) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"第%d個簡單的任務(wù)",i);
}];
// 隊列添加到隊列中,是自動執(zhí)行的
[queue addOperation:operation];
}