【文章结尾附上iOS中多线程的实现方案总结】
一、pthread
a. demo1
b. demo2
c. 对demo2中提到的 __bridge 的理解
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(run) object:nil];
[thread start]; //手动启动线程;
// 一个NSThread对象就代表一条线程。
// 线程一启动,就会在线程thread中执行self的run方法。
b. 创建线程后自动启动线程
[NSThread detachNewThreadSelector:@selector(run) toTarget:self withObject:nil];
c. 隐式创建并启动线程
[self performSelectorInBackground:@selector(run) withObject:nil];
总结:
b和c创建线程方式的优点:简单快捷;
b和c创建线程方式的缺点:无法对线程进行更详细的设置。
2.线程的状态
a. 创建线程
NSThread *thread = [[NSThreadalloc] initWithTarget:selfselector:@selector(run)object:nil];
b. 启动线程;
- (void)start NS_AVAILABLE(10_5, 2_0);
// 进入就绪状态-> 运行状态;
// 当线程任务执行完毕,自动进入死亡状态。
c. 阻塞(暂停)线程
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
// 进入阻塞状态
// 线程处理阻塞状态时在内存中的表现情况:(线程被移出可调度线程池,此时不可调度)
d. 强制停止线程
+ (void)exit;
// 进入死亡状态
// 当线程的任务结束,发生异常,或强制退出,这三种情况会导致线程的死亡。
// 线程死亡后,线程对象从内存中移除。
注意:一旦线程停止(死亡)了,就不能再次开启任务。
一张图展示线程的状态:
3. 常用属性方法
NSThread *current = [NSThreadcurrentThread];
+ (double)threadPriority;
@property double threadPriorityNS_AVAILABLE(10_6, 4_0);
// 调度优先级的取值范围是0.0 ~ 1.0,默认0.5,值越大,优先级越高;
// 但优先级高的不一定先运行,可能性更大而已。
@property (nullable,copy) NSString *nameNS_AVAILABLE(10_5, 2_0);
+ (NSThread *)mainThread NS_AVAILABLE(10_5, 2_0);
+ (BOOL)isMainThread NS_AVAILABLE(10_5, 2_0); // 是否为主线程
@property (readonly)BOOL isMainThread NS_AVAILABLE(10_5, 2_0);