GCD的常用方法總結

end5 9年前發布 | 2K 次閱讀 Objective-C IOS

 //    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(@"=======");

// });

//這個方法。常用在單例中</pre> 


 本文由用戶 end5 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!