- 同步函数 + 主队列
- 异步函数 + 主队列
- 同步函数 + 串行队列
- 异步函数 + 串行队列
- 同步函数 + 并发队列
- 异步函数 + 并发队列
- 线程间通信
- dispatch_barrier_async(栅栏)
- dispatch_after 延迟执行
- dispatch_apply 多线程遍历
- dispatch_once
- dispatch_async_f
- dispatch_group
- dispatch_source定时器
- dispatch_group_enter/dispatch_group_leave/dispatch_group_notify
- 同步函数 + 主队列:
执行dispatch_sync时主线程堵塞
执行结果:Thread ----- begin
-(void)thread {
NSLog(@"Thread ----- begin");
// 1.获得主队列
dispatch_queue_t queue = dispatch_get_main_queue();
// 2.将任务加入队列
dispatch_sync(queue, ^{
NSLog(@"%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");
}
- 异步函数 + 主队列:只在主线程中执行任务
因为是在主线程中,所以1-7任务按顺序执行
执行结果:
Thread ----- begin
Thread ----- end
1-----
2-----
3-----
4-----
5-----
6-----
7-----
-(void)thread {
NSLog(@"Thread ----- begin");
// 1.获得主队列
dispatch_queue_t queue = dispatch_get_main_queue();
// 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, ^{
sleep(1.0);
NSLog(@"4-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"5-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"6-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"7-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");
}
- 同步函数 + 串行队列:不会开启新的线程,thread方法所在的线程是main。任务是串行的,执行完1任务,再执2任务,按顺序执行
执行结果:
Thread ----- begin
1-----
2-----
Thread ----- end
-(void)thread {
NSLog(@"Thread ----- begin");
// 1.创建串行队列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
// 2.将任务加入队列
dispatch_sync(queue, ^{
NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");
}
- 异步函数 + 串行队列:会开启新的线程,但是任务是串行的,执行完1任务,再执行2任务,按顺序执行
执行结果:
Thread ----- begin
Thread ----- end
1-----
2-----
-(void)thread {
NSLog(@"Thread ----- begin");
// 1.创建串行队列
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_SERIAL);
// 2.将任务加入队列
dispatch_async(queue, ^{
NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");
}
- 同步函数 + 并发队列:不会开启新的线程,在thread方法所在的线程中,按顺序执行1,2任务
DISPATCH_QUEUE_PRIORITY_DEFAULT:默认优先级
执行结果:
Thread ----- begin
1-----
2-----
Thread ----- end
-(void)touchesBegan:(NSSet
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(thread) object:nil];
thread.name = @"thread1";
[thread start];
}
-(void)thread{
NSLog(@"Thread ----- begin");
// 1.获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2.将任务加入队列
dispatch_sync(queue, ^{
NSLog(@"1-----%@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"2-----%@", [NSThread currentThread]);
});
NSLog(@"Thread ----- end");
}
- 异步函数 + 并发队列:可以同时开启多条线程
执行结果:
Thread ----- begin
Thread ----- end
1-----
2-----
1-----
2-----
-(void)thread {
NSLog(@"Thread ----- begin");
// 1.获得全局的并发队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2.将任务加入队列
dispatch_async(queue, ^{
for (NSInteger i = 0; i<2; i++) {
NSLog(@"1-----%@", [NSThread currentThread]);
}
});
dispatch_async(queue, ^{
for (NSInteger i = 0; i<2; i++) {
NSLog(@"2-----%@", [NSThread currentThread]);
}
});
NSLog(@"Thread ----- end");
}
线程间通信
-(void)thread {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//耗时操作
dispatch_async(dispatch_get_main_queue(), ^{
//回到主线程,更新UI
});
});
}
dispatch_barrier_async:
dispatch_barrier_async,可以翻译成栅栏(barrier)
barrier作为流程控制的一种方式是用在并行环境当中。
以barrier任务为分界线,先执行barrier之前的任务1,2(1,2执行顺序不确定),在执行3,4(3,4执行顺序不确定)
执行结果:
----2-----
----1-----
----barrier-----
----3-----
----4-----
-(void)barrier {
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"----1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----2-----%@", [NSThread currentThread]);
});
dispatch_barrier_async(queue, ^{
NSLog(@"----barrier-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----4-----%@", [NSThread currentThread]);
});
}
注释掉dispatch_barrier_async后任务1-4执行顺序无序
执行结果:
----1-----
----4-----
----3-----
----2-----
-(void)barrier {
dispatch_queue_t queue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"----1-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----2-----%@", [NSThread currentThread]);
});
// dispatch_barrier_async(queue, ^{
// NSLog(@"----barrier-----%@", [NSThread currentThread]);
// });
dispatch_async(queue, ^{
NSLog(@"----3-----%@", [NSThread currentThread]);
});
dispatch_async(queue, ^{
NSLog(@"----4-----%@", [NSThread currentThread]);
});
}
延迟执行
#define DISPATCH_TIME_NOW (0ull) : unsigned long long 类型的0
#define NSEC_PER_SEC 1000000000ull : unsigned long long 类型的1000000000
dispatch_after:不是一定时间后执行相应的任务,而是一定时间后,将执行的操作加入到队列中(队列里面再分配执行的时间)所以在比如主线程每隔1/60秒执行的RunLoop,Block最快在2秒后执行,最慢在 2+1/60秒后执行。
非阻塞的执行方式,延时2秒,dispatch_get_main_queue()主线程中执行
CGFloat t = 2.0;
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(t * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
});
-
Swift延时执行方法
let time: NSTimeInterval = 2.0
let delay = dispatch_time(DISPATCH_TIME_NOW,
Int64(time * Double(NSEC_PER_SEC)))
dispatch_after(delay, dispatch_get_main_queue()) {}
其他延时方法:
此方式要求必须在主线程中执行,否则无效。
是一种非阻塞的执行方式,
可以通过NSTimer类的- (void)invalidate;取消执行。
repeats:是否重复执行
-(void)timer{
[NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(running) userInfo:nil repeats:NO];
}
此方式要求必须在主线程中执行,否则无效。
是一种非阻塞的执行方式
-(void)timer{
[self performSelector:@selector(running) withObject:nil afterDelay:2.0f];
}
dispatch_apply
第一个参数是迭代次数(这里便利10次),第二个是所在的队列(queue),第三个是当前索引(index)
dispatch_apply 和 dispatch_apply_f 是同步函数,会阻塞当前线程直到所有循环迭代执行完成。当提交到并发queue时,循环迭代的执行顺序是不确定的
执行结果:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSArray *arr = @[@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20"];
dispatch_apply(arr.count, queue, ^(size_t index) {
NSLog(@"%@, arr[%zu]:%@", [NSThread currentThread], index, arr[index]);
});
dispatch_once
dispatch_once不仅意味着代码仅会被运行一次,而且还是线程安全的,这就意味着你不需要使用诸如@synchronized之类的来防止使用多个线程或者队列时不同步的问题。
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
//程序运行期间只会执行一次
});
利用dispatch_once创建单例模式
static id _instance;
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;//记录是否执行了block
dispatch_once(&onceToken, ^{
_instance = [super allocWithZone:zone];
});
return _instance;
}
+(instancetype)shareInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_instance = [[self alloc] init];
});
return _instance;
}
-(id)copyWithZone:(NSZone *)zone{
return _instance;
}
dispatch_async_f
一般用dispatch_async(block)。dispatch_async_f(函数)
执行结果:dsafasd
-(void)asuncf{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
NSString *str = @"dsafasd";
dispatch_async_f(queue, (__bridge void *)(str), download);
}
void download(void * data)
{
NSLog(@"%@", data);
}
dispatch_group
因为是在并行队列上执行,追加字符串的2个任务执行顺不不确定,当并行队列全部执行完成后,最后到dispatch_group_notify执行操作。
执行结果:123456
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic, copy) NSString *str;
@end
-(void)group {
// 获取全局列组
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 创建一个队列组
dispatch_group_t group = dispatch_group_create();
self.str = @"";
dispatch_group_async(group, queue, ^{
self.str = [self.str stringByAppendingString:@"123"];
});
dispatch_group_async(group, queue, ^{
self.str = [self.str stringByAppendingString:@"456"];
});
dispatch_group_notify(group, queue, ^{
NSLog(@"%@", self.str);
dispatch_async(dispatch_get_main_queue(), ^{
//主线程操作
});
});
}
dispatch_source定时器
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
dispatch_queue_t queue = dispatch_get_main_queue();
// 创建一个定时器(dispatch_source_t本质还是个OC对象)
self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
// 设置定时器的各种属性(几时开始任务,每隔多长时间执行一次)
// GCD的时间参数,一般是纳秒(1秒 == 10的9次方纳秒)
// 何时开始执行第一个任务
// dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC) 比当前时间晚3秒
dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
uint64_t interval = (uint64_t)(1.0 * NSEC_PER_SEC);
dispatch_source_set_timer(self.timer, start, interval, 0);
// 设置回调
dispatch_source_set_event_handler(self.timer, ^{
NSLog(@"------------%@", [NSThread currentThread]);
});
// 启动定时器
dispatch_resume(self.timer);
}
dispatch_group_enter/dispatch_group_leave/dispatch_group_notify
目的:所有操作执行完成后再执行dispatch_group_notify内的任务
// 1.创建一个组
let group = dispatch_group_create()
// 2.将操作添加到组中
dispatch_group_enter(group)
//3.要执行的操作。。。。
// 4.离开当前组
dispatch_group_leave(group)
//5.所有操作完成后执行
dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
}