NSThread的使用

2024-01-06  本文已影响0人  iOS_tree

NSThread是一套面向对象的多线程接口。

简单的创建线程使用如下:

- (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));
//栈区大小
@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));
//线程优先级
@property NSQualityOfService qualityOfService API_AVAILABLE(macos(10.10), ios(8.0), watchos(2.0), tvos(9.0)); // read-only after the thread is started
// 当前线程执行代码的堆栈地址
@property (class, readonly, copy) NSArray<NSNumber *>*callStackReturnAddresses;
// 当前线程执行代码的堆栈信息
@property (class, readonly, copy) NSArray<NSString *> *callStackSymbols;
// 当前线程是否是主线程
@property (class, readonly) BOOL isMainThread;
// 获取主线程NSThread对象
@property (class, readonly, strong) NSThread *mainThread;

当我们继承时,重写main方法,main方法即为线程的执行函数

- (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

调用Mythread

MyThread *thread1 = [[MyThread alloc] init];
[thread1 start];
上一篇 下一篇

猜你喜欢

热点阅读