NSThread
pthread
是C语法线程管理,操作不方便,手动管理
使用相对较少
- `pthread_create()` 创建一个线程
- `pthread_exit()` 终止当前线程
- `pthread_cancel()` 中断另外一个线程的运行
- `pthread_join()` 阻塞当前的线程,直到另外一个线程运行结束
- `pthread_attr_init()` 初始化线程的属性
- `pthread_attr_setdetachstate()` 设置脱离状态的属性(决定这个线程在终
止时是否可以被结合)
- `pthread_attr_getdetachstate()` 获取脱离状态的属性
- `pthread_attr_destroy()` 删除线程的属性
- `pthread_kill()` 向线程发送一个信号
下面介绍NSThread
相关用法
- (void)start;
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
+ (void)exit;
// 获得主线程
+ (NSThread *)mainThread;
// 判断是否为主线程(对象方法)
- (BOOL)isMainThread;
// 判断是否为主线程(类方法)
+ (BOOL)isMainThread;
// 获得当前线程
NSThread *current = [NSThread currentThread];
// 线程的名字——setter方法
- (void)setName:(NSString *)n;
// 线程的名字——getter方法
- (NSString *)name;
先创建线程,再启动线程
// 1. 创建线程
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(run) object:nil];
// 2. 启动线程
[thread start]; // 线程一启动,就会在线程thread中执行self的run方法
创建线程后自动启动线程
// 1. 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self
withObject:nil];
// 新线程调用方法,里边为需要执行的任务
- (void)run {
NSLog(@"%@", [NSThread currentThread]);
}
隐式创建并启动线程
// 1. 隐式创建并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];
线程之间的通信
// 在主线程上执行操作
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg
waitUntilDone:(BOOL)wait;
// 在指定线程上执行操作
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr
withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array
NS_AVAILABLE(10_5, 2_0);
// 在当前线程上执行操作,调用 NSObject 的 performSelector:相关方法
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:
(id)object2;