Asynchronous tasks + parallel queues and asynchronous tasks + Serial queues (main queue)
Asynchronous task + parallel queue
Place asynchronous tasks in parallel queues for execution. asynchronous tasks are executed in different threads.
/* Asynchronous execution + parallel queue */-(IBAction) clickBasic1 :( UIButton *) sender {// global parallel queue dispatch_queue_t queue = dispatch_get_global_queue (queue, 0 ); // asynchronous execution of dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@ "task1: % d", I );} NSLog (@ "task1 ---- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@ "task2: % d", I);} NSLog (@ "task2 ---- % @", [NSThread currentThread]);}); dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@ "task3: % d", I );} NSLog (@ "task3 ---- % @", [NSThread currentThread]) ;});}
The running result is as follows. When asynchronous tasks and parallel queues are combined, each task is executed simultaneously in different threads.
Asynchronous task + Serial Queue (main queue)
When an asynchronous task is executed in a serial queue, the task is only executed in a new thread in order.
/* Asynchronous serial queue */-(IBAction) clickBasic3 :( id) sender {// create a serial queue dispatch_queue_t queue = dispatch_queue_create ("com. hcios ", NULL); // asynchronous execution of dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@" task1: % d ", I) ;}nslog (@" task1 ---- % @ ", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@ "task2: % d", I);} NSLog (@ "task2 ---- % @", [NSThread currentThread]) ;}); dispatch_async (queue, ^ {for (int I = 0; I <2; I ++) {NSLog (@ "task3: % d ", I);} NSLog (@" task3 ---- % @ ", [NSThread currentThread]);}
The running result is as follows. It can be seen that all tasks are executed in one thread, and after one is completed, the next task is executed.