-
多线程的实现方案:pthread / NSThread / GCD / NSOperation
-
pthread
基于C的原生多线程方法,需要手动管理线程的生命周期
//导入头文件
#import<pthread.h>
//创建线程对象
pthread_t thread;
/**
1. 线程对象地址
2. 线程的一些属性 NULL
3. 指向函数的指针
4. 函数需要接受的参数
*/
pthead_create(&thread, NULL, task, NULL);
void *task(void *param){
//任务
return NULL
}
-
NSThread
基于OC的方法,需要手动管理线程的生命周期
//创建线程1
NSThread *thread = [[NSThread alloc] initWithTarget: self selector: @selector(run:) object: @"go"];
thread.name = @"线程1";
//优先级(取值范围0.0-1.0,1.0最高,默认0.5)
thread.threadPriority = 1.0
[thread start];
//创建线程2
[NSThread detachNewThreadSelector: @selector(run:) withObject: @"go"];
//创建线程3
[self performSelectorInBackGround: @selector(run:) withObject: @"go"];
//function
-(void)run: (NSString *)param{
//任务
}