GCD:
(1)串行队列+同步请求 串行队列+异步请求
dispatch_queue_t q =dispatch_queue_create("xxxxxxx",DISPATCH_QUEUE_SERIAL);
for (int i =0; i < 10; ++i) {
dispatch_sync(q, ^{
NSLog(@"%@ %d", [NSThreadcurrentThread], i);
});
}
for (int i = 0; i <10; ++i) {
dispatch_async(q, ^{
NSLog(@"%@ %d", [NSThreadcurrentThread], i);
});
}
只要是同步:都是在主线程中,按照顺序执行。
只要是串行的 要么都运行在子线程中,要么都运行在主线程中。
(2)并行+同步 并行+异步
dispatch_queue_t q = dispatch_queue_create("cn.itcast.gcd2",DISPATCH_QUEUE_CONCURRENT);
for (int i =0; i < 10; ++i) {
dispatch_sync(q, ^{
NSLog(@"%@ %d", [NSThreadcurrentThread], i);
});
}
for (int i =0; i < 10; ++i) {
dispatch_async(q, ^{
NSLog(@"%@ %d", [NSThreadcurrentThread], i);
});
}
同步:都在主线程中按照顺序执行。
异步+并行:线程名称不确定,任务名称不确定。
(3)全局队列除了没有名字,其它的和并行队列都差不多,全局队列,供所有的APP共同使用。
全局队列不需要创建使用起来简单,直接get就可以获取:
dispatch_queue_t q =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
一般情况下,线程的优先级都设置为:DISPATCH_QUEUE_PRIORITY_DEFAULT。
(4)RunLoop
打个比方,线程相当于一条有始有终的路,RunLoop相当于一个400米的跑道。
Run loop接收输入事件来自两种不同的来源:输入源(input source)和定时源(timer source),对于输入源来说一般像socket、其它线程、输入等。定时器就是常用到的NSTimer。
比如定时器在使用的时候,在主线程中默认有RunLoop,所以定时器可以直接使用,但是在子线程中需要将这个定时器添加到RunLoop中,然后启动这个RunLoop,定时器才能正确使用。
在IOS中,每个线程都对应一个RunLoop,主线程已经创建了,子线程我们只需要配置并启动一下就可以了。默认情况下子线程中的RunLoop是不启动的。
常用的还有下面的方法:
主线程中立即执行,主线程中延迟一段时间执行。
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(<#delayInSeconds#> * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
<#code to be executed after a specified delay#>
});
dispatch_async(dispatch_get_main_queue(), ^{
})