多線程實(shí)現(xiàn)的幾種方案娘赴,主要包括pthread、NSThread询兴、GCD乃沙、NSOperation。PS:其中pthread和NSThread需要我們管理線程生命周期诗舰,比較麻煩警儒,不是很常用,我們重點(diǎn)關(guān)注GCD和NSOperation眶根。This is Operation蜀铲。
NSOperation的核心將操作添加到隊(duì)列中,是對(duì)GCD技術(shù)的一種面向?qū)ο蟮膶?shí)現(xiàn)方式属百。NSOperation是一個(gè)抽象類记劝,通過其子類NSInvocationOperation和NSBlockOperation來實(shí)現(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ù)雜代碼比較多的場(chǎng)景
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, ^{
// 耗時(shí)操作,加載一張圖片
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忧额,比較適合操作簡(jiǎn)單代碼少的場(chǎng)景
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"一個(gè)簡(jiǎn)單的任務(wù)");
}];
[operation start];
- NSOperationQueue操作隊(duì)列,管理多個(gè)并發(fā)任務(wù)愧口。多個(gè)操作添加到隊(duì)列中睦番,自動(dòng)執(zhí)行。
// 1 創(chuàng)建隊(duì)列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
// 2 創(chuàng)建多個(gè)操作
for (int i = 0; i < 10; i++) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"第%d個(gè)簡(jiǎn)單的任務(wù)",i);
}];
// 隊(duì)列添加到隊(duì)列中耍属,是自動(dòng)執(zhí)行的
[queue addOperation:operation];
}