- 同步函數 + 主隊列
- 異步函數 + 主隊列
- 同步函數 + 串行隊列
- 異步函數 + 串行隊列
- 同步函數 + 并發隊列
- 異步函數 + 并發隊列
- 線程間通信
- 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-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
2-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
3-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
4-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
5-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
6-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
7-----<NSThread: 0x7fe690405a40>{number = 1, name = main}
-(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-----<NSThread: 0x7faf10604e80>{number = 1, name = main}
2-----<NSThread: 0x7faf10604e80>{number = 1, name = main}
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-----<NSThread: 0x7f917044f030>{number = 3, name = (null)}
2-----<NSThread: 0x7f917044f030>{number = 3, name = (null)}
-(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-----<NSThread: 0x7fd66ae16720>{number = 3, name = thread1}
2-----<NSThread: 0x7fd66ae16720>{number = 3, name = thread1}
Thread ----- end
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
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-----<NSThread: 0x7fd86b706bc0>{number = 3, name = (null)}
2-----<NSThread: 0x7fd86b625900>{number = 2, name = (null)}
1-----<NSThread: 0x7fd86b706bc0>{number = 3, name = (null)}
2-----<NSThread: 0x7fd86b625900>{number = 2, name = (null)}
-(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-----<NSThread: 0x7f9982503140>{number = 6, name = (null)}
----1-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----barrier-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----3-----<NSThread: 0x7f9982748d90>{number = 5, name = (null)}
----4-----<NSThread: 0x7f9982503140>{number = 6, name = (null)}
-(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-----<NSThread: 0x7f94d3725df0>{number = 3, name = (null)}
----4-----<NSThread: 0x7f94d379a910>{number = 5, name = (null)}
----3-----<NSThread: 0x7f94d3463810>{number = 4, name = (null)}
----2-----<NSThread: 0x7f94d344f320>{number = 2, name = (null)}
-(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時,循環迭代的執行順序是不確定的
執行結果:
<NSThread: 0x7f9f40c08b20>{number = 1, name = main}, arr[0]:11
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[1]:12
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[3]:14
<NSThread: 0x7f9f40f21450>{number = 2, name = (null)}, arr[2]:13
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[5]:16
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[6]:17
<NSThread: 0x7f9f40c08b20>{number = 1, name = main}, arr[4]:15
<NSThread: 0x7f9f40f21450>{number = 2, name = (null)}, arr[7]:18
<NSThread: 0x7f9f40e10660>{number = 3, name = (null)}, arr[8]:19
<NSThread: 0x7f9f40e0d2f0>{number = 4, name = (null)}, arr[9]:20
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
}