您的位置:首页 > 其它

多线程基础基础

2016-01-02 23:55 323 查看
一 NSThread

-(void)testThread1

{

NSString*param = @"Task test";

NSThread*thread = [[NSThread alloc] initWithTarget:self selector:@selector(onExecuteTask1:)object:param];

[thread start];

[NSThread sleepForTimeInterval:3];

}

-(void)onExecuteTask1:(NSString *) param

{

@autoreleasepool

{

NSLog(@"thread = %@, param = %@", [NSThread currentThread], param);

}

}

二 performSelector 系列

-(void)run

{

[self performSelectorInBackground:@selector(doWork) withObject:nil];

}

/* 后台线程 */

-(void)doWork

{

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];

/* 长时间处理 */

// ...

/* 切换到主线程 */

[self performSelectorOnMainThread:@selector(doneWork) withObject:nil waituntilDone:NO];

[pool drain];

}

-(void)doneWork

{

/* 主线程,更新ui */

}

三 NSOperationQueue和 NSOperation

NSOperation类:一个要执行的任务类;

NSOperationQueue类:任务执行队列、线程池。可以添加NSOperation实例和代码块:

- (void)addOperation:(NSOperation *)op;

- (void)addOperationWithBlock:(void(^)(void))block;

@implementationMyOperation

-(void)main

{

@autoreleasepool

{

NSLog(@"thread = %@, param = %@", [NSThread currentThread], _param);

}

}

@end

NSInvocationOperation类,继承自NSOperation类。它可以方便地异步执行某个方法,跟NSThread一样的用法。如下:

NSInvocationOperation *task_a = [[NSInvocationOperation alloc] initWithTarget:selfselector:@selector(onTask:) object:param_a];

代码如下:

-(void)testThread

{

NSString *param_a = @"Task 1";

NSString *param_b = @"Task 2";

NSString *param_c = @"Task 3";

//新建任务

NSInvocationOperation *task_a = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(onTask:) object:param_a];

NSOperation *task_b = [[MyOperation alloc] initWithParam:param_b];

//依赖关系:任务b执行完后才执行任务a

[task_a addDependency:task_b];

//新建线程池

NSOperationQueue *taskQueue = [[NSOperationQueue alloc] init];

//设置最大的并发线程数

[taskQueue setMaxConcurrentOperationCount:3];

//添加任务(NSOperation对象)到线程池,由线程池调度执行

[taskQueue addOperation:task_a];

[taskQueue addOperation:task_b];

//添加任务(代码块)到线程池,由线程池调度执行

[taskQueue addOperationWithBlock:^{

NSLog(@"%@", param_c);

}];

[NSThread sleepForTimeInterval:3];

}

-(void)onTask:(NSString *) param

{

@autoreleasepool

{

NSLog(@"thread = %@, param = %@", [NSThread currentThread], param);

}

}

四 GCD

Grand Central Dispatch (GCD)是Apple开发的一个多核编程的较新的解决方法。它主要用于优化应用程序以支持多核处理器以及其他对称多处理系统。它是一个在线程池模式的基础上执行的并行任务。GCD的相关方法,均以“dispatch_”开发,例如:

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT,
0), ^(void){

//线程执行

dispatch_async(dispatch_get_main_queue(), ^(void){

//主线程更新UI

});

});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: