創(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]);
}