iOS 多線程(一)---> NSThread

NSThread的使用

No.1:NSThread創(chuàng)建線程

NSThread有三種創(chuàng)建方式:

  • init方式
  • detachNewThreadSelector創(chuàng)建好之后自動(dòng)啟動(dòng)
  • performSelectorInBackground創(chuàng)建好之后也是直接啟動(dòng)
/** 方法一,需要start */
NSThread *thread1 = [[NSThread alloc] initWithTarget:self selector:@selector(doSomething1:) object:@"NSThread1"];
// 線程加入線程池等待CPU調(diào)度,時(shí)間很快,幾乎是立刻執(zhí)行
[thread1 start];
 
/** 方法二,創(chuàng)建好之后自動(dòng)啟動(dòng) */
[NSThread detachNewThreadSelector:@selector(doSomething2:) toTarget:self withObject:@"NSThread2"];
 
/** 方法三,隱式創(chuàng)建,直接啟動(dò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的類方法

  • 返回當(dāng)前線程
// 當(dāng)前線程
[NSThread currentThread];
NSLog(@"%@",[NSThread currentThread]);
 
// 如果number=1,則表示在主線程,否則是子線程
打印結(jié)果:{number = 1, name = main}
  • 阻塞休眠
//休眠多久
[NSThread sleepForTimeInterval:5];
//休眠到指定時(shí)間
[NSThread sleepUntilDate:[NSDate date]];
  • 類方法補(bǔ)充
//退出線程
[NSThread exit];
//判斷當(dāng)前線程是否為主線程
[NSThread isMainThread];
//判斷當(dāng)前線程是否是多線程
[NSThread isMultiThreaded];
//主線程的對(duì)象
NSThread *mainThread = [NSThread mainThread];

No.3:NSThread的一些屬性

//線程是否在執(zhí)行
thread.isExecuting;
//線程是否被取消
thread.isCancelled;
//線程是否完成
thread.isFinished;
//是否是主線程
thread.isMainThread;
//線程的優(yōu)先級(jí),取值范圍0.0到1.0,默認(rèn)優(yōu)先級(jí)0.5,1.0表示最高優(yōu)先級(jí),優(yōu)先級(jí)高,CPU調(diào)度的頻率高
 thread.threadPriority;
至此,NSThread的相關(guān)內(nèi)容敘述完畢,如果不足,請(qǐng)批評(píng)指正 , 謝謝 !
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 在說多線程之前,首先要明白線程,進(jìn)程 線程和進(jìn)程 進(jìn)程: 系統(tǒng)中正在運(yùn)行的程序,稱為一個(gè)進(jìn)程 每個(gè)進(jìn)程,都在自己獨(dú)...
    時(shí)來運(yùn)不轉(zhuǎn)閱讀 607評(píng)論 0 3
  • 一、多線程基礎(chǔ) 基本概念 進(jìn)程進(jìn)程是指在系統(tǒng)中正在運(yùn)行的一個(gè)應(yīng)用程序每個(gè)進(jìn)程之間是獨(dú)立的,每個(gè)進(jìn)程均運(yùn)行在其專用且...
    AlanGe閱讀 653評(píng)論 0 0
  • 本文選譯自《Threading Programming Guide》。 導(dǎo)語(yǔ) 線程技術(shù)作為在單個(gè)應(yīng)用程序中并發(fā)執(zhí)行...
    巧巧的二表哥閱讀 2,597評(píng)論 4 24
  • 在這篇文章中,我將為你整理一下 iOS 開發(fā)中幾種多線程方案,以及其使用方法和注意事項(xiàng)。當(dāng)然也會(huì)給出幾種多線程的案...
    伯恩的遺產(chǎn)閱讀 275,637評(píng)論 251 2,328
  • 湖泊星羅棋布,陌上桑蠶怵然, 茅房胡琴鼓瑟,塞上羌笛頻吹, 漢調(diào),秦弦,如何? 唯愛鐘鼓。
    董之堯閱讀 255評(píng)論 1 1

友情鏈接更多精彩內(nèi)容