NSThread創(chuàng)建及簡單使用

創(chuàng)建方法

    //方法一
    NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(threadAction) object:nil];
    //啟動線程
    [thread1 start];
    
   // 注意:object:后面跟的是自定義方法有參數(shù)時接受的參數(shù),以下方法都是一樣
    

    //方法二 沒有返回值,不需要調(diào)用start方法
    [NSThread detachNewThreadSelector:@selector(threadAction) toTarget:self withObject:nil];

    
    //方法三
    [self performSelectorInBackground:@selector(threadAction) withObject:nil];

    
    //方法四 自定義線程
    CustomThread *customThread = [[CustomThread alloc]init];
    //啟動方法調(diào)用main方法的話,就相當(dāng)于調(diào)用了一個普通方法,還是在主線程中
    // [self main];//這種調(diào)用是錯誤的
    //啟動線程,新的線程會執(zhí)行相應(yīng)線程生成的main方法,并且會開辟一個新的線程
    [customThread start];
}

 //自定義類.m 文件內(nèi)容
 #import "CustomThread.h"

@implementation CustomThread

- (void)main{
    
    NSLog(@"threadPriority的優(yōu)先級:%lf",[NSThread threadPriority]);
    
    NSLog(@"threadCallMethod是否是主線程:%d",[[NSThread currentThread] isMainThread]);
}

@end

退出線程

    
    //1線程的推出(只能退出還沒有執(zhí)行的線程)
    [NSThread exit];

    
    
    //指定某個線程退出
    //(1)先標(biāo)記thread1狀態(tài)是cancel
    [self performSelector:@selector(cancelThread1:) withObject:thread1 afterDelay:1];

    //給線程綁定狀態(tài)的方法
    - (void)cancelThread1:(NSThread *)thread{
    
    [thread cancel];
}


//線程實現(xiàn)的方法
- (void)threadAction{
    
    //(2)延遲2秒,判斷當(dāng)前線程是否被取消的狀態(tài)
    [NSThread sleepForTimeInterval:2];
    if ([[NSThread currentThread]isCancelled]) {
        //如果是,退出線程
        [NSThread exit];
    }
    
    
    NSLog(@"-----優(yōu)先級:%lf",[NSThread threadPriority]);
    NSLog(@"------是否是主線程:%d",[[NSThread currentThread]isMainThread]);
    
}

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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