学习多线程09(之前跟着小码哥视频学习了多线程,准备把学到的东西放到网上,便于参考。仅有视频,所以所有文字都是自己打的,同时也温习一下多线程)
博客原地址:http://blog.csdn.net/leemin_ios/article/details/51192425
GCD的各种队列
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
[self asynConcurrent];
[self synConcurrent];
[self asynSerial];
[self synMain];
}
/** 同步函数+主队列=不会开线程死循环 */
-(void)synMain
{
//1.1创建串行队列
dispatch_queue_t queue = dispatch_get_main_queue();
//2.将任务加入队列
dispatch_sync(queue, ^{
NSLog(@"1当前队列:%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2当前队列:%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"3当前队列:%@",[NSThread currentThread]);
});
}
/** 异步函数+串行队列=只开启1条新的线程 */
-(void)asynSerial
{
//1.1创建串行队列
dispatch_queue_t queue = dispatch_queue_create("limin_ios", DISPATCH_QUEUE_SERIAL);
//2.将任务加入队列
dispatch_async(queue, ^{
NSLog(@"1当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3当前队列:%@",[NSThread currentThread]);
});
}
/** 同步函数+并发任务=不会开启新的线程,在主线程完成任务 */
-(void)synConcurrent
{
//1.1创建全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
//2.将任务加入队列
dispatch_sync(queue, ^{
NSLog(@"1当前队列:%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2当前队列:%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"3当前队列:%@",[NSThread currentThread]);
});
}
/** 异步函数+并发队列 */
-(void)asynConcurrent
{
//1.创建一个并发队列
//label:相当于队列的名字 .队列的类型:DISPATCH_QUEUE_CONCURRENT并发
// dispatch_queue_t queue = dispatch_queue_create("limin_ios1", DISPATCH_QUEUE_CONCURRENT);
//1.1创建全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//2.将任务加入队列
dispatch_async(queue, ^{
NSLog(@"1当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"3当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"4当前队列:%@",[NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"当前队列:%@",[NSThread currentThread]);
});
// dispatch_release(queue);
}