喜歡我的可以關注收藏我的個人部落格: RobberJJ GCD中擷取各種類型的隊列:
//擷取串行的隊列
dispatch_queue_t singalQueue = dispatch_queue_create("single",DISPATCH_QUEUE_SERIAL);
//擷取并發執行的隊列
dispatch_queue_t concrtQueue = dispatch_queue_create("queue", DISPATCH_QUEUE_CONCURRENT);
//擷取主隊列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//擷取全局的隊列(并發的)
dispatch_queue_t gobalqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
<h6>串行隊列異步執行任務</h6>
- 異步具有建立新線程的能力,會開辟新線程去執行任務;
- 按照串行的方式去執行任務。
如下調用方式可參考:
- (void)singalAsynQueue{
//建立串行隊列
dispatch_queue_t singalQueue = dispatch_queue_create("singal", DISPATCH_QUEUE_SERIAL);
//在singalQueue中異步執行任務(該方法實作在本文後續中)
[self asynWithQueue: singalQueue];
}
<h6>串行隊列同步執行任務</h6>
- 同步不具有建立新的線程的能力, 不會開辟新的線程去執行任務,會在目前的程式的主線程中去執行任務;
- (void)singalSynQueue{
//在singalQueue中同步執行任務(該方法實作在本文後續中)
[self synWithQueue: singalQueue];
<h6>并發隊列異步執行任務(常用)</h6>
- 異步具有建立新的線程的能力,會開辟新的線程去執行任務,不會在目前的程式的主線程中去執行任務;
- 按照并發的方式去執行任務。
- (void)concrtAsynQueue{
//建立并發執行的隊列
// dispatch_queue_t concrtQueue = dispatch_queue_create("concrtQueue", DISPATCH_QUEUE_CONCURRENT);
//擷取全局的隊列
dispatch_queue_t concrtQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//在concrtQueue中異步執行任務(該方法實作在本文後續中)
[self asynWithQueue:concrtQueue];
<h6>并發隊列同步執行任務</h6>
- 按照同步的方式去執行任務。
- (void)concrtSynQueue{
//在concrtQueue中同步執行任務(該方法實作在本文後續中)
[self synWithQueue:concrtQueue];
<h6>主隊列的同步(會造成程式的死鎖)</h6>
如下:
- (void)mainSynQueue{
//擷取主隊列
dispatch_queue_t mainQueue = dispatch_get_main_queue();
//在mainQueue中同步執行任務(該方法實作在本文後續中)
[self synWithQueue:mainQueue];
<h6>主隊列的異步(在主線程中順序執行)</h6>
新添加到主隊列中的任務會放到隊列的最尾部,等到目前主線程中的任務結束之後然後再從隊列的頭部取出依次執行(FIFO)先進先出。
- (void)mainAsynQueue{
//在mainQueue中異步執行任務(該方法實作在本文後續中)
[self asynWithQueue:mainQueue];
<h6>異步方法的實作</h6>
- (void)asynWithQueue:(dispatch_queue_t)queue{
NSLog(@"%@",[NSThread currentThread]);
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]);
});
NSLog(@"--------end------------");
}
<h6>同步方法的實作</h6>
- (void)synWithQueue:(dispatch_queue_t)queue{
NSLog(@"%@",[NSThread currentThread]);
dispatch_sync(queue, ^{
NSLog(@"----1----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----2----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----3----%@",[NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"----4----%@",[NSThread currentThread]);
});
NSLog(@"--------end------------");
}