NSThread的使用
No.1:NSThread創(chuàng)建線程
NSThread有三種創(chuàng)建方式:
- init方式
- detachNewThreadSelector創(chuàng)建好之后自動啟動
- performSelectorInBackground創(chuàng)建好之后也是直接啟動
/** 方法一蠕啄,需要start */
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething1:) object:@"NSThread1"];
// 線程加入線程池等待CPU調度,時間很快,幾乎是立刻執(zhí)行
[thread1 start];
/** 方法二,創(chuàng)建好之后自動啟動 */
[NSThread detachNewThreadSelector:@selector(doSomething2:) toTarget:self withObject:@"NSThread2"];
/** 方法三娶靡,隱式創(chuàng)建擂找,直接啟動 */
[self performSelectorInBackground:@selector(doSomething3:) withObject:@"NSThread3"];
- (void)doSomething1:(NSObject *)object {
// 傳遞過來的參數(shù)
NSLog(@"%@",object);
NSLog(@"doSomething1:%@",[NSThread currentThread]);
}
- (void)doSomething2:(NSObject *)object {
NSLog(@"%@",object);
NSLog(@"doSomething2:%@",[NSThread currentThread]);
}
- (void)doSomething3:(NSObject *)object {
NSLog(@"%@",object);
NSLog(@"doSomething3:%@",[NSThread currentThread]);
}
No.2:NSThread的類方法
- 返回當前線程
// 當前線程
[NSThread currentThread];
NSLog(@"%@",[NSThread currentThread]);
// 如果number=1邑雅,則表示在主線程坑质,否則是子線程
打印結果:{number = 1, name = main}
- 阻塞休眠
//休眠多久
[NSThread sleepForTimeInterval:5];
//休眠到指定時間
[NSThread sleepUntilDate:[NSDate date]];
- 類方法補充
//退出線程
[NSThread exit];
//判斷當前線程是否為主線程
[NSThread isMainThread];
//判斷當前線程是否是多線程
[NSThread isMultiThreaded];
//主線程的對象
NSThread *mainThread = [NSThread mainThread];
No.3:NSThread的一些屬性
//線程是否在執(zhí)行
thread.isExecuting;
//線程是否被取消
thread.isCancelled;
//線程是否完成
thread.isFinished;
//是否是主線程
thread.isMainThread;
//線程的優(yōu)先級硬梁,取值范圍0.0到1.0前硫,默認優(yōu)先級0.5,1.0表示最高優(yōu)先級荧止,優(yōu)先級高屹电,CPU調度的頻率高
thread.threadPriority;