详解IOS串行队列与并行队列进行同步或者异步的实例

2020-01-21 00:17:52丽君


- (void)testAsync {
  dispatch_queue_t serialQueue = dispatch_queue_create("com.zyt.queue", DISPATCH_QUEUE_SERIAL);
  dispatch_queue_t concurrentQueue = dispatch_queue_create("com.zyt.queue", DISPATCH_QUEUE_CONCURRENT);

  NSLog(@"====serialQueue====");
  for (int i = 0; i<10; i++) {
    dispatch_async(serialQueue, ^{
      [NSThread sleepForTimeInterval:0.3];
      NSLog(@"==>%@ async serial XXX>%d", [NSThread currentThread], i);
    });
  }

  NSLog(@"====concurrentQueue====");
  for (int i = 0; i<10; i++) {
    dispatch_async(concurrentQueue, ^{
      [NSThread sleepForTimeInterval:0.3];
      NSLog(@"==>%@ async concurrent ====>%d", [NSThread currentThread], i*i);
    });
  }
}
`

结果如下:


2017-03-01 01:45:36.125 Demo ====serialQueue====
2017-03-01 01:45:36.125 Demo ====concurrentQueue====
2017-03-01 01:45:36.494 {number = 3, name = (null)} async concurrent ====>0
2017-03-01 01:45:36.494 {number = 5, name = (null)} async concurrent ====>4
2017-03-01 01:45:36.494 {number = 4, name = (null)} async concurrent ====>1
2017-03-01 01:45:36.494 {number = 6, name = (null)} async concurrent ====>16
2017-03-01 01:45:36.494 {number = 8, name = (null)} async serial XXX>0
2017-03-01 01:45:36.494 {number = 7, name = (null)} async concurrent ====>9
2017-03-01 01:45:36.494 {number = 9, name = (null)} async concurrent ====>25
2017-03-01 01:45:36.494 {number = 11, name = (null)} async concurrent ====>49
2017-03-01 01:45:36.494 {number = 10, name = (null)} async concurrent ====>36
2017-03-01 01:45:36.501 {number = 13, name = (null)} async concurrent ====>81
2017-03-01 01:45:36.501 {number = 12, name = (null)} async concurrent ====>64
2017-03-01 01:45:36.869 {number = 8, name = (null)} async serial XXX>1
2017-03-01 01:45:37.244 {number = 8, name = (null)} async serial XXX>2
2017-03-01 01:45:37.615 {number = 8, name = (null)} async serial XXX>3
2017-03-01 01:45:37.986 {number = 8, name = (null)} async serial XXX>4
2017-03-01 01:45:38.358 {number = 8, name = (null)} async serial XXX>5
2017-03-01 01:45:38.730 {number = 8, name = (null)} async serial XXX>6
2017-03-01 01:45:39.103 {number = 8, name = (null)} async serial XXX>7
2017-03-01 01:45:39.472 {number = 8, name = (null)} async serial XXX>8
2017-03-01 01:45:39.842 {number = 8, name = (null)} async serial XXX>9

testSync方法是在主线程中调用的,结果看到使用的串行队列的异步任务会开启一个子线程执行任务,任务的调度是串行的
使用并行队列的异步任务会开启多个子线程并行的处理任务,任务的先后顺序是不固定的,任务的调度方式是并行的

总结

同步任务:和使用的队列无关,不会开启子线程处理任务,会在当前的线程中串行的调度任务,即一个任务完成之后继续下一个任务,如果同步任务在主线程中调用,会阻塞主线程