NSThread
查看NSThread.h中的接口:
類方法不返回NSThread實例,直接在其他線程里面執(zhí)行任務。
+ (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才能執(zhí)行,執(zhí)行完任務,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));
線程優(yōu)先級,類方法,實例化NSThread后調用,優(yōu)先級高的任務先被調度。這個屬性即將廢棄,改為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通知相應的線程去執(zhí)行。這套機制生效的前提是onThread的thread的runloop是開啟的。如果子線程runloop未開啟,就不會執(zhí)行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中的任務順序由主線程執(zhí)行。沒有起到在子線程中并發(fā)。所有不要顯式的調用main方法,如[thread main];
一旦NSThread的子類重寫了main()方法,[thread start]就只會調用main方法里面的任務,block和selector都不會執(zhí)行。
- (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