NSThread是一套面向?qū)ο蟮亩嗑€程接口粘室。
簡單的創(chuàng)建線程使用如下:
- (void)ThreadRun:(id)object {
NSLog(@"%s %@",__FUNCTION__,object);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(ThreadRun:) object:@"text"];
[thread1 start];
}
NSThread的屬性如下:
//線程名稱
@property (nullable, copy) NSString *name API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
//棧區(qū)大小
@property NSUInteger stackSize API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
//是否為主線程
@property (readonly) BOOL isMainThread API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0));
//線程優(yōu)先級(jí)
@property NSQualityOfService qualityOfService API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // read-only after the thread is started
// 當(dāng)前線程執(zhí)行代碼的堆棧地址
@property (class, readonly, copy) NSArray<NSNumber *>*callStackReturnAddresses;
// 當(dāng)前線程執(zhí)行代碼的堆棧信息
@property (class, readonly, copy) NSArray<NSString *> *callStackSymbols;
// 當(dāng)前線程是否是主線程
@property (class, readonly) BOOL isMainThread;
// 獲取主線程N(yùn)SThread對(duì)象
@property (class, readonly, strong) NSThread *mainThread;
當(dāng)我們繼承時(shí)践剂,重寫main方法船万,main方法即為線程的執(zhí)行函數(shù)
- (void)main API_AVAILABLE(macos(10.5), ios(2.0), watchos(2.0), tvos(9.0)); // thread body method
示例代碼如下:
@interface MyThread : NSThread
@end
@implementation MyThread
- (void)main {
NSLog(@"%@",[NSThread currentThread]);
NSLog(@"%s",__FUNCTION__);
}
@end
調(diào)用Mythread
MyThread *thread1 = [[MyThread alloc] init];
[thread1 start];