// GCD常用方法
//————————————————————————————————————————————————————————————————————————————————
//串行隊列
dispatch_queue_t queueSerial = dispatch_queue_create("jr", DISPATCH_QUEUE_SERIAL);
//並行隊列
dispatch_queue_t queueConcu = dispatch_queue_create("jr2", DISPATCH_QUEUE_CONCURRENT);
//1、循環多次使用
//(1)添加串行隊列,同步執行。可以當for循環使用(在主線程中)
// dispatch_apply(3, queueSerial, ^(size_t t) {// 參數^(size_t),需要自己加一個^(size_t t),否則有問題
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%@", [NSThread currentThread]);
// });
//(2)添加並行隊列,同步執行。可以當for循環使用(如果循環次數大於1,則開子線程)
// dispatch_apply(3, queueConcu, ^(size_t t) {// 參數^(size_t),需要自己加一個^(size_t t),否則有問題
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%@", [NSThread currentThread]);
// });
//(3)參數size_t的作用:打印的是0.1.2.3.。。的序號
// dispatch_apply(3, queueSerial, ^(size_t t) {
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%li == %@", t, [NSThread currentThread]);
// });
//(4)以上都是在主線程中進行的。如果想在子線程中執行,需要這樣做
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// dispatch_apply(3, queueConcu, ^(size_t t) {
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%li == %@", t, [NSThread currentThread]);
// });
// });
//2、分組(可以監聽組內子線程是否全部都執行完成)
// dispatch_group_t group = dispatch_group_create();
//
// dispatch_group_async(group, queueConcu, ^{
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%@", [NSThread currentThread]);
// });
// dispatch_group_async(group, queueConcu, ^{
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%@", [NSThread currentThread]);
// });
// dispatch_group_async(group, queueConcu, ^{
// [NSThread sleepForTimeInterval:1];
// NSLog(@"%@", [NSThread currentThread]);
// });
//
// dispatch_group_notify(group, queueConcu, ^{
// NSLog(@"----%@", [NSThread currentThread]);
// });
//3、延遲(寫在這個塊中的代碼都是在主線程中執行的)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[NSThread sleepForTimeInterval:2];
NSLog(@"----%@", [NSThread currentThread]);
});
NSLog(@"33333%@", [NSThread currentThread]);
timer = [NSTimer scheduledTimerWithTimeInterval:.5 target:self selector:@selector(touchesBegan) userInfo:nil repeats:YES];
//4.設置障礙(在同一隊列中,只要添加了障礙,不管有沒有創建多線程,他後邊的任務都要跨國這個障礙,即等待這個障礙結束)
// dispatch_async(queueConcu, ^{
// NSLog(@"11111");
// });
//
// dispatch_barrier_async(queueConcu, ^{
// [NSThread sleepForTimeInterval:5];
// });
//
// dispatch_async(queueConcu, ^{
// NSLog(@"11111");
// });
// dispatch_async(queueConcu, ^{
// NSLog(@"11111");
// });
//5、讓代碼只執行一次
// static dispatch_once_t oneToken;
// dispatch_once(&oneToken, ^{
// NSLog(@"=======");
// });
//這個方法。常用在單例中