NSThread
查看NSThread.h中的接口:
类方法不返回NSThread实例,直接在其他线程里面执行任务。
+ (void)detachNewThreadWithBlock:(void(^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullableid)argument;
实例方法返回NSThread对象,需要调用start,或者main才能执行,执行完任务,ARC自动回收NSThread对象。
- (instancetype)init NS_AVAILABLE(10_5,2_0) NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument NS_AVAILABLE(10_5,2_0);
- (instancetype)initWithBlock:(void(^)(void))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
线程优先级,类方法,实例化NSThread后调用,优先级高的任务先被调度。这个属性即将废弃,改为qualityOfService。
+ (double)threadPriority;
+ (BOOL)setThreadPriority:(double)p;
@property double threadPriority NS_AVAILABLE(10_6,4_0);// To be deprecated; use qualityOfService below
@property NSQualityOfService qualityOfService NS_AVAILABLE(10_10,8_0);// read-only after the thread is started
线程Sleep,类方法,将当前线程sleep。
+ (void)sleepUntilDate:(NSDate *)date;
+ (void)sleepForTimeInterval:(NSTimeInterval)ti;
NSObject (NSThreadPerformAdditions):以下category方法,在delay后,把事件放到runloop里面,runloop通知相应的线程去执行。这套机制生效的前提是onThread的thread的runloop是开启的。如果子线程runloop未开启,就不会执行selector,如果waitUntilDone为YES,此时就会阻塞当前线程。
@interface NSObject (NSThreadPerformAdditions)
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait modes:(nullableNSArray *)array;
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullableid)arg waitUntilDone:(BOOL)wait;
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullableid)arg waitUntilDone:(BOOL)wait modes:(nullableNSArray *)array NS_AVAILABLE(10_5,2_0);
- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullableid)arg waitUntilDone:(BOOL)wait NS_AVAILABLE(10_5,2_0);
// equivalent to the first method with kCFRunLoopCommonModes
- (void)performSelectorInBackground:(SEL)aSelector withObject:(nullableid)arg NS_AVAILABLE(10_5,2_0);
start方法和main方法
You should never invoke this method directly. You should always start your thread by invoking the start method.
开启两个线程NSThread,调用main方法,两个NSThread中的任务顺序由主线程执行。没有起到在子线程中并发。所有不要显式的调用main方法,如[thread main];
一旦NSThread的子类重写了main()方法,[thread start]就只会调用main方法里面的任务,block和selector都不会执行。
- (void)cancel NS_AVAILABLE(10_5,2_0);
- (void)start NS_AVAILABLE(10_5,2_0);
- (void)main NS_AVAILABLE(10_5,2_0);// thread body method
@end
网友评论