問(wèn)題
1.練習(xí)題1
當(dāng)前代碼 在主隊(duì)列中執(zhí)行
// 這里是函數(shù)開始執(zhí)行的地方
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_async(queue, ^{
NSLog(@"1");
// 這句代碼的本質(zhì)是往Runloop中添加定時(shí)器
[self performSelector:@selector(test) withObject:nil afterDelay:.0];
NSLog(@"3");
});
- (void)test
{
NSLog(@"2");
}
2.練習(xí)題2
當(dāng)前代碼在主線程當(dāng)中運(yùn)行
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"1");
}];
[thread start];
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
- (void)test
{
NSLog(@"2");
}
3.練習(xí)題3
當(dāng)前代碼在主線程當(dāng)中運(yùn)行
NSThread *thread = [[NSThread alloc] initWithBlock:^{
NSLog(@"1");
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}];
[thread start];
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
[self performSelector:@selector(test) onThread:thread withObject:nil waitUntilDone:YES];
- (void)test
{
NSLog(@"2");
}
答案
1.練習(xí)題1
結(jié)果: 打印 1 和 3
分析: 子線程當(dāng)中,默認(rèn)不開啟runloop [self performSelector:@selector(test) withObject:nil afterDelay:.0];這句代碼本質(zhì)是向當(dāng)前子線程的runloop 當(dāng)中添加了一個(gè)定時(shí)器,但是子線程當(dāng)中runloop 默認(rèn)不會(huì)啟動(dòng),所以不會(huì)打印 2
解決方案:
在NSlog(@"3")前面添加 [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];就可以了
2.練習(xí)題2
結(jié)果:打印 1 之后奔潰
分析,由于子線程start 之后,沒(méi)有相應(yīng)開啟runloop 給子線程保活,子線程已經(jīng)執(zhí)行完 block 就已經(jīng)死掉了,之后在在子線程中執(zhí)行 test函數(shù),肯定就會(huì)奔潰.
解決方案:
在NSlog(@"1")下面添加保活代碼:
[[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
3.練習(xí)題3
結(jié)果打印1 2 之后奔潰
分析: [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
只會(huì)執(zhí)行一次,相當(dāng)于保證了一次,當(dāng)?shù)谝淮螆?zhí)行完之后,線程也就死掉來(lái)了,第二次在執(zhí)行test 函數(shù),也就導(dǎo)致奔潰
解決方案:
while (1){
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} 這樣就保證了線程一直存在