iOS多线程:NSThread
2020-04-28 本文已影响0人
码小菜
别墅
目录
一,线程创建
二,线程通信
三,线程状态
一,线程创建
1,实例方法
initWithTarget:
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread = [[NSThread alloc] initWithTarget:self
selector:@selector(performTask)
object:nil];
[thread start];
}
- (void)performTask {
NSLog(@"%s---%@", __func__, [NSThread currentThread]);
}
// 打印
-[ViewController performTask]---<NSThread: 0x60000072a700>{number = 6, name = (null)}
initWithBlock:
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"initWithBlock---%@", [NSThread currentThread]);
}];
[thread start];
}
// 打印
initWithBlock---<NSThread: 0x600002098e80>{number = 6, name = (null)}
2,类方法
detachNewThreadSelector:
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadSelector:@selector(performTask)
toTarget:self
withObject:nil];
}
- (void)performTask {
NSLog(@"%s---%@", __func__, [NSThread currentThread]);
}
// 打印
-[ViewController performTask]---<NSThread: 0x6000037c50c0>{number = 6, name = (null)}
detachNewThreadWithBlock:
- (void)viewDidLoad {
[super viewDidLoad];
[NSThread detachNewThreadWithBlock:^{
NSLog(@"detachNewThreadWithBlock---%@", [NSThread currentThread]);
}];
}
// 打印
detachNewThreadWithBlock---<NSThread: 0x600001e4b640>{number = 6, name = (null)}
二,线程通信
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *thread = [[NSThread alloc] initWithBlock:^{
// 保证线程不退出
[[NSRunLoop currentRunLoop] run];
}];
[thread start];
[self performSelector:@selector(requestData)
onThread:thread
withObject:nil
waitUntilDone:NO]; // 在任务执行完毕之前是否阻塞当前线程
}
- (void)requestData {
NSLog(@"在子线程请求数据---%@", [NSThread currentThread]);
[self performSelectorOnMainThread:@selector(refreshUI)
withObject:nil
waitUntilDone:NO];
}
- (void)refreshUI {
NSLog(@"回主线程刷新UI---%@", [NSThread currentThread]);
}
// 打印
在子线程请求数据---<NSThread: 0x60000192cb40>{number = 7, name = (null)}
回主线程刷新UI---<NSThread: 0x600001952140>{number = 1, name = main}
三,线程状态
1,图解
线程状态2,代码
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"1---新建");
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"3---运行");
NSLog(@"执行任务中...");
NSLog(@"4---阻塞");
[NSThread sleepForTimeInterval:3.0];
NSLog(@"5---就绪");
NSLog(@"6---运行");
NSLog(@"执行任务中...");
NSLog(@"7---死亡");
}];
NSLog(@"2---就绪");
[thread start];
}
// 打印
16:04:36.579845+0800 Demo[60081:6857038] 1---新建
16:04:36.580071+0800 Demo[60081:6857038] 2---就绪
16:04:36.590601+0800 Demo[60081:6857250] 3---运行
16:04:36.590989+0800 Demo[60081:6857250] 执行任务中...
16:04:36.591309+0800 Demo[60081:6857250] 4---阻塞
16:04:39.594615+0800 Demo[60081:6857250] 5---就绪
16:04:39.595011+0800 Demo[60081:6857250] 6---运行
16:04:39.595297+0800 Demo[60081:6857250] 执行任务中...
16:04:39.595646+0800 Demo[60081:6857250] 7---死亡
3,可调度线程池
- 新建---就绪:系统会将线程放入可调度线程池中
- 运行---阻塞:系统会将线程从可调度线程池中移除
- 阻塞---就绪:系统会将线程再次放入可调度线程池中