直接上代碼
示例1:
@interface TBViewController()
//隊(duì)列
@PRoperty(nonatomic,strong)NSOperationQueue *queue;
@end
//隊(duì)列的暫停和繼續(xù)(在storyboard中拖兩個(gè)按鈕,分別為暫停、繼續(xù),連線)
//暫停
-(IBAction)pause
{
if(self.queue.operationCount == 0){
NSLog(@"無(wú)操作");
return;
}
//掛起》暫停 暫停的是隊(duì)列,讓隊(duì)列暫時(shí)不再派發(fā)任務(wù)
NSLog(@"暫停");
[self.queue setSuspended:YES];
}
//繼續(xù)
-(IBAction)resumue
{
if(self.queue.operationCount == 0){
NSLog(@"無(wú)操作");
return;
}
NSLog(@"繼續(xù)");
[self.queue setSuspended:NO];
}
//懶加載
-(NSOperationQueue *)queue
{
if(_queue == nil){
_queue = [[NSOperationQueue alloc]init];
}
return _queue;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self opDemo1];
}
//同時(shí)并發(fā)線程數(shù)量
-(void)opDemo1
{
//線程開(kāi)啟的隊(duì)列是由GCD底層決定的,程序員不能參與
/*
設(shè)置最大并發(fā)數(shù)的好處:線程開(kāi)啟有消耗
3G: 2~3條線程,線程少,流量少,省錢,省電
WIFI: 5~6條線程,線程多,效率高,流量大,不花錢,可以隨時(shí)充電
*/
self.queue maxConcurrentOperationCount = 3;//最大并發(fā)數(shù)量
for(int i = 0;i < 100; i ++){
[self.queue addOperationWithBlock:^{
//阻塞
[NSThread sleepForTimeInterval:2];
NSLog(@"%@ %d",[NSThread currentThread];)
}];
}
}
示例2:操作的依賴-》操作的執(zhí)行順序
-(void)opDemo3
{
/*
例如:
1、下載小電影的壓縮包
2、解壓縮
3、保存文件
4、通知用戶
*/
NSBlockOperation*op1 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"下載:%@",[NSThread currentThread]);
}];
NSBlockOperation*op2 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"解壓縮:%@",[NSThread currentThread]);
}];
NSBlockOperation*op3 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"保存:%@",[NSThread currentThread]);
}];
NSBlockOperation*op4 = [NSBlockOperation blockOperationWithBlock:^{
NSLog(@"通知用戶:%@",[NSThread currentThread]);
}];
//依賴
[op2 addDependency:op1];
[op3 addDependency:op3];
[op4 addDependency:op3];
//循環(huán)依賴(一定不要出現(xiàn))
[op1 addDependency:op4];
//異步的 waitUntilFinished 等待所有操作完成在繼續(xù)
[self.queue addOperations:@[op1,op2,op3] waitUntilFinished:NO];
//主隊(duì)列
[[NSOperationQueue mainQueue] addOperation:op4];
}
總結(jié):
/*
NSOperation
1.是對(duì)GCD的封裝
2、是OC的,面向?qū)ο蟮模褂酶尤菀?/p>
3、提供了一些特殊的方法,是GCD不容易實(shí)現(xiàn)的,例如:最大并發(fā)線程數(shù)量、暫停和繼續(xù)
4、可以指定操作的依賴關(guān)系,依賴關(guān)系是可以跨隊(duì)列的
5、自定義的隊(duì)列,是并發(fā)隊(duì)列,操作是異步任務(wù)
GCD
1、是C語(yǔ)言的,難度有點(diǎn)大
2、once
3、after
4、GCD還有非常多復(fù)雜的功能
*/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注