线程有4中延时执行的方法
NSSleep NSTime GCD_After self perfomS
在后台处理线程问题
[self performSelectorInBackground:@selector(longTimeOperation:) withObject:@"hm"];
通过C 语言的pthread来创建线程
首先导入<pthread.h>框架
pthread_t threadId;
id str = @"hm";
pthread_create(&threadId, NULL, run, (__bridge void *)(str));
#pragma mark - pthread 演练
void *run(void *param) {
NSString *str = (__bridge NSString *)(param);
NSLog(@"%@ %@", [NSThread currentThread], str);
return NULL;
}
NSThread 是苹果官方提供的,使用起来比 pthread 更加面向对象,简单易用,可以直接操作线程对象。不过也需要需要程序员自己管理线程的生命周期(主要是创建),我们在开发的过程中偶尔使用 NSThread。比如我们会经常调用[NSThread currentThread]来显示当前的进程信息。
// 1. 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
// 2. 启动线程
[thread start]; // 线程一启动,就会在线程thread中执行self的run方法
//开启一个线程并且自启动
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];